content
stringlengths 7
1.05M
|
---|
#!/usr/bin/python3
'''
BubbleSort.py
by Xiaoguang Zhu
'''
array = []
print("Enter at least two numbers to start bubble-sorting.")
print("(You can end inputing anytime by entering nonnumeric)")
# get numbers
while True:
try:
array.append(float(input(">> ")))
except ValueError: # exit inputing
break
print("\nThe array you've entered was:"); print(array)
print("\nNow sorting...")
# sorting
for x in range(len(array)-1, 0, -1):
for y in range(x):
if array[y] > array[y+1]:
array[y], array[y+1] = array[y+1], array[y]
print(array)
# output
print("\nAll done! Now the moment of truth!")
print(array)
|
medida = float(input("uma distancai em metros: "))
cm = medida * 100
mm = medida * 1000
dm = medida / 10
dam = medida * 1000000
hm = medida / 100
km = medida * 0.001
ml = medida * 0.000621371
m = medida * 100000
print("A medida de {:.0f}m corresponde a {:.0f} mm \n{:.0f} cm \n{:.0f} dm \n{:.0f} dam \n{:.0f} hm \n{:.2f} km \n{:.2f} ml" .format (medida, cm, mm, dm, dam, hm, km, ml))
|
def create_supervised_data(env, agents, num_runs=50):
val = []
# the data threeple
action_history = []
predict_history = []
mental_history = []
character_history = []
episode_history = []
traj_history = []
grids = []
ep_length = env.maxtime
filler = env.get_filler()
obs = env.reset(setting=setting, num_visible=num_goals)
for ep in tqdm.tqdm(range(num_runs*eps_per_run)):
buffer_s = [np.zeros(obs[0].shape) for _ in range(env.maxtime)]
if (ep % eps_per_run) == eps_per_run-1:
obs = env.reset(setting=setting, num_visible=num_goals)
else:
obs = env.reset()
if ep % eps_per_run == 0:
episode_number = 0
#clear ep_history here?
for agent in agents:
if not unarbitrary_prefs:
agent.reset_prefs()
else:
agent.hardcode_prefs()
prevact = None
prevpos = None
agentpos = agents[0].pos
episode_time = 0
while not env.done:
if rendering and ((ep % eps_per_run) == eps_per_run-1):
env.render()
buffer_s.append(obs[0])
actions = [agent.action(torch.FloatTensor([buffer_s[-env.maxtime:]]).cuda()),]
agentpos = agents[0].pos
thistraj = env.get_trajectory(agentpos, prevact, prevpos)
prevpos = agentpos
#without agent position, thisact of none is pretty meaningless
prevact = actions[0]
traj_history += [thistraj, ]
#moved this to before following if
episode_time += 1
if ((ep % eps_per_run) == eps_per_run-1):
# each step in last episode
#episode number is 3
if visualize:
render_path(env, ep, episode_time, vispath)
#print(actions)
run = np.zeros((eps_per_run, ep_length, *filler.shape))
if eps_per_run > 1:
run[-episode_number-1:-1] = episode_history[-episode_number:]
episode = np.zeros((ep_length, *filler.shape))
episode[ep_length-episode_time:] = traj_history[-episode_time]
run[-1] = episode
shortterm = np.asarray(traj_history[-1])
action_history += [one_hot(5, actions[0]),]
character_history += [run,]
mental_history += [episode,]
predict_history += [shortterm,]
if not env.full_test:
break
obs, _, _, = env.step(actions)
# end of episode
episode = np.zeros((ep_length, *filler.shape))
episode[ep_length-episode_time:] = traj_history[-episode_time:]
episode_history += [episode, ]
episode_number += 1
return character_history, mental_history, predict_history, action_history
def format_data_torch(data, **train_kwargs):
char = np.asarray(data[0]).astype('float32')
# (N, Ep, F, W, H, C) = first.shape
#first.reshape((N, Ep, F, C, H, W))
char = np.swapaxes(char, 3, 5)
mental = np.asarray(data[1]).astype('float32')
# (N, F, W, H, C) = first.shape
#first.reshape((N, F, C, H, W))
mental = np.swapaxes(mental, 2, 4)
query = np.asarray(data[2][:]).astype('float32')
# (N, W, H, C) = second.shape
#second.reshape((N, C, H, W))
query = np.swapaxes(query, 1, 3)
act = np.asarray(data[3][:]).astype('int32')
char1 = torch.Tensor(char).cuda()#[:, 0, :, :, :, :]
mental1 = torch.Tensor(mental).cuda()
query1 = torch.Tensor(query).cuda()#[:, 0, :, :, :]
act1 = torch.Tensor(act).cuda()
dataset = torch.utils.data.TensorDataset(char1, mental1, query1, act1)
return torch.utils.data.DataLoader(dataset, **train_kwargs)
def supervised_training(env, agents, data):
dummies = [Dummy(steps, model) for agent in agents]
class DummyAgent():
'''
railroads the agent for some steps,
then switches to an alternate model.
railroaded steps should be included in
environment's test condition,
returned as the final value of reset()
predefined strategies after the railroaded
steps are compared with the alt model's output
'''
def __init__(self, railroad, strategies, model):
self.n = -1
self.length = len(railroad)
self.model = model
self.rails = railroad
self.strats = strategies
def choose_action(self, obs):
if n <= self.length:
self.n += 1
return self.railroad[self.n], [0 for x in self.strats]
else:
self.n += 1
act = self.model.choose_action(obs)
return act, [act == x[self.n] for x in self.strats]
def reset(railroad, strategies):
self.length = len(railroad)
self.rails = railroad
self.strats = strategies
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: list):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return None
if len(lists) == 1:
return lists[0]
node_result = self.merge_two_sorted_lists(lists.pop(), lists.pop())
while lists:
node_result = self.merge_two_sorted_lists(node_result, lists.pop())
return node_result
def merge_two_sorted_lists(self, node_a, node_b):
head_node = ListNode(-1)
cur_node = head_node
while node_a and node_b:
if node_a.val < node_b.val:
cur_node.next = node_a
node_a = node_a.next
else:
cur_node.next = node_b
node_b = node_b.next
cur_node = cur_node.next
cur_node.next = node_a or node_b
return head_node.next
|
def create_path(path:str):
"""
:param path:path is the relative path from the pixel images folder
:return: return the relative path from roots of project
"""
return current_path + path
#a function name is before the parameters and after the def
#function parameters: the values that the function knows, inside the parantheses
#function typehinting: tells the code that it should be a string...
#docstrings: tells what the function does, what parameters are, what it returns |
def rep_hill(x, n):
"""Dimensionless production rate for a gene repressed by x.
Parameters
----------
x : float or NumPy array
Concentration of repressor.
n : float
Hill coefficient.
Returns
-------
output : NumPy array or float
1 / (1 + x**n)
"""
return 1.0 / (1.0 + x ** n)
def act_hill(x, n):
"""Dimensionless production rate for a gene activated by x.
Parameters
----------
x : float or NumPy array
Concentration of activator.
n : float
Hill coefficient.
Returns
-------
output : NumPy array or float
x**n / (1 + x**n)
"""
return 1.0 - rep_hill(x, n)
def aa_and(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
activators with AND logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first activator.
y : float or NumPy array
Concentration of second activator.
nx : float
Hill coefficient for first activator.
ny : float
Hill coefficient for second activator.
Returns
-------
output : NumPy array or float
x**nx * y**ny / (1 + x**nx) / (1 + y**ny)
"""
return x ** nx * y ** ny / (1.0 + x ** nx) / (1.0 + y ** ny)
def aa_or(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
activators with OR logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first activator.
y : float or NumPy array
Concentration of second activator.
nx : float
Hill coefficient for first activator.
ny : float
Hill coefficient for second activator.
Returns
-------
output : NumPy array or float
(x**nx + y**ny + x**nx * y**ny) / (1 + x**nx) / (1 + y**ny)
"""
denom = (1.0 + x ** nx) * (1.0 + y ** ny)
return (denom - 1.0) / denom
def aa_or_single(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
activators with OR logic in the absence of leakage with single
occupancy.
Parameters
----------
x : float or NumPy array
Concentration of first activator.
y : float or NumPy array
Concentration of second activator.
nx : float
Hill coefficient for first activator.
ny : float
Hill coefficient for second activator.
Returns
-------
output : NumPy array or float
(x**nx + y**ny) / (1 + x**nx + y**ny)
"""
num = x ** nx + y ** ny
return num / (1.0 + num)
def rr_and(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
repressors with AND logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first repressor.
y : float or NumPy array
Concentration of second repressor.
nx : float
Hill coefficient for first repressor.
ny : float
Hill coefficient for second repressor.
Returns
-------
output : NumPy array or float
1 / (1 + x**nx) / (1 + y**ny)
"""
return 1.0 / (1.0 + x ** nx) / (1.0 + y ** ny)
def rr_and_single(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
repressors with AND logic in the absence of leakage with
single occupancy.
Parameters
----------
x : float or NumPy array
Concentration of first repressor.
y : float or NumPy array
Concentration of second repressor.
nx : float
Hill coefficient for first repressor.
ny : float
Hill coefficient for second repressor.
Returns
-------
output : NumPy array or float
1 / (1 + x**nx + y**ny)
"""
return 1.0 / (1.0 + x ** nx + y ** ny)
def rr_or(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
repressors with OR logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first repressor.
y : float or NumPy array
Concentration of second repressor.
nx : float
Hill coefficient for first repressor.
ny : float
Hill coefficient for second repressor.
Returns
-------
output : NumPy array or float
(1 + x**nx + y**ny) / (1 + x**nx) / (1 + y**ny)
"""
return (1.0 + x ** nx + y ** ny) / (1.0 + x ** nx) / (1.0 + y ** ny)
def ar_and(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by one
activator and one repressor with AND logic in the absence of
leakage.
Parameters
----------
x : float or NumPy array
Concentration of activator.
y : float or NumPy array
Concentration of repressor.
nx : float
Hill coefficient for activator.
ny : float
Hill coefficient for repressor.
Returns
-------
output : NumPy array or float
x ** nx / (1 + x**nx) / (1 + y**ny)
"""
return x ** nx / (1.0 + x ** nx) / (1.0 + y ** ny)
def ar_or(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by one
activator and one repressor with OR logic in the absence of
leakage.
Parameters
----------
x : float or NumPy array
Concentration of activator.
y : float or NumPy array
Concentration of repressor.
nx : float
Hill coefficient for activator.
ny : float
Hill coefficient for repressor.
Returns
-------
output : NumPy array or float
(1 + x**nx + x**nx * y**ny)) / (1 + x**nx) / (1 + y**ny)
"""
return (1.0 + x ** nx * (1.0 + y ** ny)) / (1.0 + x ** nx) / (1.0 + y ** ny)
def ar_and_single(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by one
activator and one repressor with AND logic in the absence of
leakage with single occupancy.
Parameters
----------
x : float or NumPy array
Concentration of activator.
y : float or NumPy array
Concentration of repressor.
nx : float
Hill coefficient for activator.
ny : float
Hill coefficient for repressor.
Returns
-------
output : NumPy array or float
x ** nx / (1 + x**nx + y**ny)
"""
return x ** nx / (1.0 + x ** nx + y ** ny)
def ar_or_single(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by one
activator and one repressor with OR logic in the absence of
leakage with single occupancy.
Parameters
----------
x : float or NumPy array
Concentration of activator.
y : float or NumPy array
Concentration of repressor.
nx : float
Hill coefficient for activator.
ny : float
Hill coefficient for repressor.
Returns
-------
output : NumPy array or float
(1 + x**nx) / (1 + x**nx + y**ny)
"""
return (1.0 + x ** nx) / (1.0 + x ** nx + y ** ny)
|
n = int(input())
vip_guest = set()
regular_guest = set()
for _ in range(n):
reservation_code = input()
if reservation_code[0].isdigit():
vip_guest.add(reservation_code)
else:
regular_guest.add(reservation_code)
command = input()
while command != "END":
if command[0].isdigit():
vip_guest.discard(command)
else:
regular_guest.discard(command)
command = input()
missing_guest = len(vip_guest) + len(regular_guest)
print(missing_guest)
for vip in sorted(vip_guest):
print(vip)
for regular in sorted(regular_guest):
print(regular)
|
class alttprException(Exception):
pass
class alttprFailedToRetrieve(Exception):
pass
class alttprFailedToGenerate(Exception):
pass
|
EXPECTED_TABULATED_HTML = """
<table>
<thead>
<tr>
<th>category</th>
<th>date</th>
<th>downloads</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">2.6</td>
<td align="left">2018-08-15</td>
<td align="right">51</td>
</tr>
<tr>
<td align="left">2.7</td>
<td align="left">2018-08-15</td>
<td align="right">63,749</td>
</tr>
<tr>
<td align="left">3.2</td>
<td align="left">2018-08-15</td>
<td align="right">2</td>
</tr>
<tr>
<td align="left">3.3</td>
<td align="left">2018-08-15</td>
<td align="right">40</td>
</tr>
<tr>
<td align="left">3.4</td>
<td align="left">2018-08-15</td>
<td align="right">6,095</td>
</tr>
<tr>
<td align="left">3.5</td>
<td align="left">2018-08-15</td>
<td align="right">20,358</td>
</tr>
<tr>
<td align="left">3.6</td>
<td align="left">2018-08-15</td>
<td align="right">35,274</td>
</tr>
<tr>
<td align="left">3.7</td>
<td align="left">2018-08-15</td>
<td align="right">6,595</td>
</tr>
<tr>
<td align="left">3.8</td>
<td align="left">2018-08-15</td>
<td align="right">3</td>
</tr>
<tr>
<td align="left">null</td>
<td align="left">2018-08-15</td>
<td align="right">1,019</td>
</tr>
</tbody>
</table>
"""
EXPECTED_TABULATED_MD = """
| category | date | downloads |
|----------|------------|----------:|
| 2.6 | 2018-08-15 | 51 |
| 2.7 | 2018-08-15 | 63,749 |
| 3.2 | 2018-08-15 | 2 |
| 3.3 | 2018-08-15 | 40 |
| 3.4 | 2018-08-15 | 6,095 |
| 3.5 | 2018-08-15 | 20,358 |
| 3.6 | 2018-08-15 | 35,274 |
| 3.7 | 2018-08-15 | 6,595 |
| 3.8 | 2018-08-15 | 3 |
| null | 2018-08-15 | 1,019 |
"""
EXPECTED_TABULATED_RST = """
.. table::
========== ============ ===========
category date downloads
========== ============ ===========
2.6 2018-08-15 51
2.7 2018-08-15 63,749
3.2 2018-08-15 2
3.3 2018-08-15 40
3.4 2018-08-15 6,095
3.5 2018-08-15 20,358
3.6 2018-08-15 35,274
3.7 2018-08-15 6,595
3.8 2018-08-15 3
null 2018-08-15 1,019
========== ============ ===========
""" # noqa: W291
EXPECTED_TABULATED_TSV = """
"category" \t "date" \t "downloads"
"2.6" \t "2018-08-15" \t 51
"2.7" \t "2018-08-15" \t 63,749
"3.2" \t "2018-08-15" \t 2
"3.3" \t "2018-08-15" \t 40
"3.4" \t "2018-08-15" \t 6,095
"3.5" \t "2018-08-15" \t 20,358
"3.6" \t "2018-08-15" \t 35,274
"3.7" \t "2018-08-15" \t 6,595
"3.8" \t "2018-08-15" \t 3
"null" \t "2018-08-15" \t 1,019
""" # noqa: W291
|
# Runtime: 84 ms, faster than 22.95% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree.
# Memory Usage: 23.1 MB, less than 91.67% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# Method 1
# ans = [None]
# def lca(node):
# if not node:
# return False
# mid = (node is p or node is q)
# left = lca(node.left)
# right = lca(node.right)
# if mid + left + right >= 2:
# ans[0] = node
# return mid or left or right
# lca(root)
# return ans[0]
# Method 2
# Time: O(n)
# Space: O(h)
if root is None:
return None
if root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
else:
return left or right |
load(
"//tensorflow/core/platform:rules_cc.bzl",
"cc_library",
)
def poplar_cc_library(**kwargs):
""" Wrapper for inserting poplar specific build options.
"""
if not "copts" in kwargs:
kwargs["copts"] = []
copts = kwargs["copts"]
copts.append("-Werror=return-type")
cc_library(**kwargs)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Question:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
'''
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
digits = 1
while x/digits >= 10:
digits *= 10
while digits > 1:
right = x % 10
left = int(x/digits)
if left != right:
return False
x = int((x%digits) / 10)
digits /= 100
return True
|
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class MonitoringStation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id, label, coord, typical_range,
river, town):
self.station_id = station_id
self.measure_id = measure_id
# Handle case of erroneous data where data system returns
# '[label, label]' rather than 'label'
self.name = label
if isinstance(label, list):
self.name = label[0]
self.coord = coord
self.typical_range = typical_range
self.river = river
self.town = town
self.latest_level = None
def __repr__(self):
d = "Station name: {}\n".format(self.name)
d += " id: {}\n".format(self.station_id)
d += " measure id: {}\n".format(self.measure_id)
d += " coordinate: {}\n".format(self.coord)
d += " town: {}\n".format(self.town)
d += " river: {}\n".format(self.river)
d += " typical range: {}".format(self.typical_range)
return d
def typical_range_consistent(self):
"""Return True if the data is consistent and False if
the data is inconsistent or unavailable."""
# inconsistent if data is unavailable
if self.typical_range == None:
return False
# inconsistent if low range is higher than high range
elif self.typical_range[0] > self.typical_range[1]:
return False
# else consistent
else:
return True
def relative_water_level(self):
"""Returns the latest water level as a fraction of the typical range.
Returns None if data is not available or is inconsistent"""
# Return None if data is not available or is inconsistent
if self.latest_level == None:
return None
elif self.typical_range_consistent() == False:
return None
# Return latest water level as a fraction of the typical range
else:
return (self.latest_level - self.typical_range[0])/(
self.typical_range[1] - self.typical_range[0])
def inconsistent_typical_range_stations(stations):
"""Returns a list of stations that have inconsistent data. The input
is stations, which is a list of MonitoringStation objects."""
# return list of stations with inconsistent data ranges
return [station.name for station in stations if station.typical_range_consistent() == False] |
a = input("Enter the string:")
b = a.find("@")
c = a.find("#")
print("The original string is:",a)
print("The substring between @ and # is:",a[b+1:c]) |
def fahrenheit_to_celsius(F):
'''
Function to compute Celsius from Fahrenheit
'''
K = fahrenheit_to_kelvin(F)
C = kelvin_to_celsius(K)
return C
|
def read_lines(file_path):
with open(file_path, 'r') as handle:
return [line.strip() for line in handle]
def count_bits(numbers):
counts = [0] * len(numbers[0])
for num in numbers:
for i, bit in enumerate(num):
counts[i] += int(bit)
return counts
lines = read_lines('test.txt')
counts = count_bits(lines)
total_lines = len(lines)
gamma = [int(c > total_lines/2) for c in counts]
epsilon = [int(not bit) for bit in gamma]
gamma = int(''.join(str(bit) for bit in gamma), 2)
epsilon = int(''.join(str(bit) for bit in epsilon), 2)
print(f'Part 1:\n {gamma * epsilon}\n')
oxygen_rating = lines
co2_rating = lines
for i in range(len(oxygen_rating[0])):
counts = count_bits(oxygen_rating)
total = len(oxygen_rating)
more_common_bit = int(counts[i] >= total/2)
oxygen_rating = [num for num in oxygen_rating if int(num[i]) == more_common_bit]
if len(oxygen_rating) == 1:
break
for i in range(len(co2_rating[0])):
counts = count_bits(co2_rating)
total = len(co2_rating)
more_common_bit = int(counts[i] >= total/2)
co2_rating = [num for num in co2_rating if int(num[i]) != more_common_bit]
if len(co2_rating) == 1:
break
oxygen_rating = int(oxygen_rating[0], 2)
co2_rating = int(co2_rating[0], 2)
print('Part 2')
print(f' Oxygen rating: {oxygen_rating}')
print(f' CO2 rating: {co2_rating}')
print(' ' + str(oxygen_rating * co2_rating))
|
famous_name = "albert einstein"
motto = "A person who never made a mistake never tried anything new."
message = famous_name.title() + "once said, " + '"' + motto + '"'
print(message) |
JIRA_DOMAIN = {'RD2': ['innodiv-hwacom.atlassian.net','innodiv-hwacom.atlassian.net'],
'RD5': ['srddiv5-hwacom.atlassian.net']}
API_PREFIX = 'rest/agile/1.0'
# project_id : column_name
STORY_POINT_COL_NAME = {'10005': 'customfield_10027',
'10006': 'customfield_10027',
'10004': 'customfield_10026'
}
|
class PixelMeasurer:
def __init__(self, coordinate_store, is_one_calib_block, correction_factor):
self.coordinate_store = coordinate_store
self.is_one_calib_block = is_one_calib_block
self.correction_factor = correction_factor
def get_distance(self, calibration_length):
distance_per_pixel = calibration_length / self.pixel_distance_calibration()
if not self.is_one_calib_block:
calibration_difference = float(self.pixel_distance_calibration_side()) / \
float(self.pixel_distance_calibration())
distance_correction = 1 - self.correction_factor*(1 - calibration_difference)
return self.pixel_distance_between_wheels() * distance_per_pixel * distance_correction
else:
return self.pixel_distance_between_wheels() * distance_per_pixel
def get_left_wheel_midpoint(self):
points = self.coordinate_store.get_left_wheel_points()
return int(abs(points[0][0] + points[1][0]) / 2)
def get_right_wheel_midpoint(self):
points = self.coordinate_store.get_right_wheel_points(is_one_calib_block=self.is_one_calib_block)
return int(abs(points[0][0] + points[1][0]) / 2)
def pixel_distance_between_wheels(self):
return abs(self.get_right_wheel_midpoint() - self.get_left_wheel_midpoint())
def pixel_distance_calibration(self):
calibration_points = self.coordinate_store.get_middle_calib_points()
return abs(calibration_points[0][0] - calibration_points[1][0])
def pixel_distance_calibration_side(self):
calibration_points = self.coordinate_store.get_side_calib_points()
return abs(calibration_points[0][0] - calibration_points[1][0])
|
# Programming for the Puzzled -- Srini Devadas
# You Will All Conform
# Input is a vector of F's and B's, in terms of forwards and backwards caps
# Output is a set of commands (printed out) to get either all F's or all B's
# Fewest commands are the goal
caps = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F']
cap2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F']
def pleaseConform(caps):
# Initialization
start = 0
forward = 0
backward = 0
intervals = []
# Determine intervals where caps are on in the same direction
for i in range(len(caps)):
if caps[start] != caps[i]:
# each interval is a tuple with 3 elements (start, end, type)
intervals.append((start, i - 1, caps[start]))
if caps[start] == 'F':
forward += 1
else:
backward += 1
start = i
# Need to add the last interval after for loop completes execution
intervals.append((start, len(caps) - 1, caps[start]))
if caps[start] == 'F':
forward += 1
else:
backward += 1
## print (intervals)
## print (forward, backward)
if forward < backward:
flip = 'F'
else:
flip = 'B'
for t in intervals:
if t[2] == flip:
# Exercise: if t[0] == t[1] change the printing!
if t[0] == t[1]:
print('Person at position', t[0], 'flip your cap!')
else:
print('People in positions', t[0], 'through', t[1], 'flip your caps!')
pleaseConform(caps)
##pleaseConform(cap2)
|
s=input()
t=input()
ss=sorted(map(s.count,set(s)))
tt=sorted(map(t.count,set(t)))
print('Yes' if ss==tt else 'No')
|
def anagrams(word, words):
agrams = []
s1 = sorted(word)
for i in range (0, len(words)):
s2 = sorted(words[i])
if s1 == s2:
agrams.append(words[i])
return agrams |
#!/usr/bin/env python
"""
WhatIsCode
This extremely simple script was an inspiration driven by a combination of
Paul Ford's article on Bloomberg Business Week, "What is Code?"[1] and
Haddaway's song, "What is Love"[2]. It is probably best enjoyed while
watching an 8-bit demake of the song[3], or 16-bit if you prefer[4]. :-)
[1] http://www.bloomberg.com/graphics/2015-paul-ford-what-is-code/
[2] https://en.wikipedia.org/wiki/What_Is_Love_%28Haddaway_song%29
[3] https://www.youtube.com/watch?v=CT8t_1JXWn8
[4] https://www.youtube.com/watch?v=I2ufcU7I9-I
Usage Instructions/Examples:
In a REPL or other program:
# Import the module.
from what_is_code import WhatIsCode
# Instantiate the object.
song = WhatIsCode()
# Output the song.
song.sing()
As a standalone script on the shell:
Make sure the script is executable:
chmod +x what_is_code.py
Run the script:
./what_is_code.py
Enjoy! :-)
Copyright 2015 Carlo Costino
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class WhatIsCode(object):
def __init__(self):
"""
Initialize the main refrain and verses used throughout the song.
"""
self.main_refrain = [
'What is code?',
'Program don\'t crash now',
'Don\'t crash now, again',
]
self.first_verse = [
'I don\'t know why you don\'t work',
'I type things in right, but you just fail',
'So what is True?',
'And what is False?',
'Gimme a break',
]
self.second_verse = [
'Oh, I give up, nothing I do',
'Will work in this app, that I called foo',
'I wrote some tests',
'And they all pass',
'But my app fails',
]
self.third_verse = [
'Can you please just work, just work as I want',
'This is insane, wasted time',
'I thought this was easy, I though this was simple',
'Is it code?',
]
@property
def secondary_refrain(self):
"""
The secondary refrain is just the last two parts of the main refrain.
"""
return self.main_refrain[1:]
@property
def tertiary_refrain(self):
"""
A tertiary refrain appears once toward the end of the song made up of
a substring of the last line in the main refrain.
"""
return [self.main_refrain[2][:-7]] * 2
@property
def what_is_code(self):
"""
"What is code?" is repeated many times throughout the song, so let's
make it easy to repeat on its own.
"""
return self.main_refrain[0]
def sing_line(self, line=''):
"""
Outputs a single string with a newline character at the end for proper
formatting.
"""
return '%s\n' % line
def sing_lines(self, lines=[]):
"""
Outputs a list of strings with a newline character at the end of each
string, including the last one.
"""
return '%s\n' % '\n'.join(lines)
def sing(self):
"""
Sings the entire song by printing out every line found within it.
Yes, this is brute force and somewhat ugly, but also simple.
"""
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.secondary_refrain))
print(self.sing_line(self.what_is_code))
print('Damn it\n')
print(self.sing_lines(self.first_verse))
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.second_verse))
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.main_refrain))
print(self.sing_line(self.what_is_code))
print(self.sing_line(self.what_is_code))
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.tertiary_refrain))
print(self.sing_lines(self.third_verse))
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.main_refrain))
print('Damn\n')
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.main_refrain))
print(self.sing_lines(self.secondary_refrain))
print(self.sing_lines(self.secondary_refrain))
print(self.sing_line(self.what_is_code))
# If this module is being run as a standalone script, output the song
# immediately.
if __name__ == '__main__':
song = WhatIsCode()
song.sing()
|
initialScore = int(input())
def count_solutions(score, turn):
if score > 50 or turn > 4:
return 0
if score == 50:
return 1
result = count_solutions(score + 1, turn + 1)
for i in range(2, 13):
result += 2 * count_solutions(score + i, turn + 1)
return result
print(count_solutions(initialScore, 0))
|
#!/usr/bin/env python3
def gcd(a, b):
if a == 0 :
return b
return gcd(b%a, a)
a = 12000
b = 8642
print(gcd(a, b))
|
def solve():
n = int(input())
k = list(map(int,input().split()))
hashmap = dict()
j = 0
ans = 0
c = 0
for i in range(n):
if k[i] in hashmap and hashmap[k[i]] > 0:
while i > j and k[i] in hashmap and hashmap[k[i]] > 0:
hashmap[k[j]] -= 1
j += 1
c -= 1
hashmap[k[i]] = 1
c += 1
ans = max(ans,c)
print(ans)
if __name__ == '__main__':
solve() |
# Here the rate is set for Policy flows, local to a compute, which is
# lesser than policy flows across computes
expected_flow_setup_rate = {}
expected_flow_setup_rate['policy'] = {
'1.04': 6000, '1.05': 9000, '1.06': 10000, '1.10': 10000, '2.10': 13000}
expected_flow_setup_rate['nat'] = {
'1.04': 4200, '1.05': 6300, '1.06': 7500, '1.10': 7500, '2.10': 10000}
|
# Dynamic Programming Python implementation of Min Cost Path
# problem
R = 3
C = 3
def minCost(cost, m, n):
# Instead of following line, we can use int tc[m+1][n+1] or
# dynamically allocate memoery to save space. The following
# line is used to keep te program simple and make it working
# on all compilers.
tc = [[0 for x in range(C)] for x in range(R)]
tc[0][0] = cost[0][0]
# Initialize first column of total cost(tc) array
for i in range(1, m+1):
tc[i][0] = tc[i-1][0] + cost[i][0]
# Initialize first row of tc array
for j in range(1, n+1):
tc[0][j] = tc[0][j-1] + cost[0][j]
# Construct rest of the tc array
for i in range(1, m+1):
for j in range(1, n+1):
tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]
return tc[m][n]
# Driver program to test above functions
cost = [[1, 2, 3],
[4, 8, 2],
[1, 5, 3]]
print(minCost(cost, 2, 2))
#O(mn) |
"""
迭代器 --> yield
"""
class CommodityController:
def __init__(self):
self.__commoditys = []
def add_commodity(self, cmd):
self.__commoditys.append(cmd)
def __iter__(self):
index = 0
yield self.__commoditys[index]
index += 1
yield self.__commoditys[index]
index += 1
yield self.__commoditys[index]
controller = CommodityController()
controller.add_commodity("屠龙刀")
controller.add_commodity("倚天剑")
controller.add_commodity("芭比娃娃")
for item in controller:
print(item)
# iterator = controller.__iter__()
# while True:
# try:
# item = iterator.__next__()
# print(item)
# except StopIteration:
# break
|
print('=' * 12 + 'Desafio 53' + '=' * 12)
frase = input('Digite sua frase: ')
frase = frase.strip().replace(" ","").upper()
tamanho = len(frase)
contador = 0
igual = 0
for i in range(tamanho - 1, -1, -1):
if frase[contador] == frase[i]:
igual += 1
contador += 1
if contador == tamanho:
print('A frase é um palíndromo!')
else:
print('A frase não é um palíndromo!')
|
def create_box(input_corners):
x = (float(input_corners[0][0]), float(input_corners[1][0]))
y = (float(input_corners[0][1]), float(input_corners[1][1]))
windmill_lats, windmill_lons = zip(*[
(max(x), max(y)),
(min(x), max(y)),
(min(x), min(y)),
(max(x), min(y)),
(max(x), max(y))
])
return windmill_lats, windmill_lons
|
class Label:
@staticmethod
def from_str(value):
for l in Label._get_supported_labels():
if l.to_str() == value:
return l
raise Exception("Label by value '{}' doesn't supported".format(value))
@staticmethod
def from_int(value):
assert(isinstance(value, int))
for l in Label._get_supported_labels():
if l.to_int() == value:
return l
raise Exception("Label by value '{}' doesn't supported".format(value))
@staticmethod
def from_uint(value):
assert(isinstance(value, int) and value >= 0)
for l in Label._get_supported_labels():
if l.to_uint() == value:
return l
raise Exception("Label by unsigned value '{}' doesn't supported".format(value))
@staticmethod
def _get_supported_labels():
supported_labels = [
PositiveLabel(),
NegativeLabel()
]
return supported_labels
def to_str(self):
raise NotImplementedError()
def to_int(self):
raise NotImplementedError()
def to_uint(self):
raise Exception("Not implemented exception")
def __eq__(self, other):
assert(isinstance(other, Label))
return self.to_int() == other.to_int()
def __ne__(self, other):
assert(isinstance(other, Label))
return self.to_int() != other.to_int()
class PositiveLabel(Label):
def to_str(self):
return 'pos'
def to_int(self):
return int(1)
def to_uint(self):
return int(1)
class NegativeLabel(Label):
def to_str(self):
return 'neg'
def to_int(self):
return int(-1)
def to_uint(self):
return int(2)
|
'''70. Climbing Stairs
Easy
3866
127
Add to List
Share
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step'''
n = int(input())
a,b = 1,2
for i in range(n-1):
a,b = b,a+b
print(a) |
RESOURCES = {
'posts': {
'schema': {
'title': {
'type': 'string',
'minlength': 3,
'maxlength': 30,
'required': True,
'unique': False
},
'body': {
'type': 'string',
'required': True,
'unique': True
},
'published': {
'type': 'boolean',
'default': False
},
'category': {
'type': 'objectid',
'data_relation': {
'resource': 'categories',
'field': '_id',
'embeddable': True
},
'required': True
},
'tags': {
'type': 'list',
'default': [],
'schema': {
'type': 'objectid',
'data_relation': {
'resource': 'tags',
'field': '_id',
'embeddable': True
}
}
}
},
},
'categories': {
'schema': {
'name': {
'type': 'string',
'minlength': 2,
'maxlength': 10,
'required': True,
'unique': True
}
},
'item_title': 'category',
},
'tags': {
'schema': {
'name': {
'type': 'string',
'minlength': 2,
'maxlength': 10,
'required': True,
'unique': True
}
}
}
}
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Modified by: Zhengying Liu, Isabelle Guyon
"""An example of code submission for the AutoDL challenge.
It implements 3 compulsory methods: __init__, train, and test.
model.py follows the template of the abstract class algorithm.py found
in folder AutoDL_ingestion_program/.
To create a valid submission, zip model.py together with an empty
file called metadata (this just indicates your submission is a code submission
and has nothing to do with the dataset metadata.
"""
class Model(object):
"""Fully connected neural network with no hidden layer."""
def __init__(self, metadata):
pass
|
pkgname = "python-sphinx-removed-in"
pkgver = "0.2.1"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
checkdepends = ["python-sphinx"]
depends = ["python-sphinx"]
pkgdesc = "Sphinx extension for versionremoved and removed-in directives"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-3-Clause"
url = "https://github.com/MrSenko/sphinx-removed-in"
source = f"$(PYPI_SITE)/s/sphinx-removed-in/sphinx-removed-in-{pkgver}.tar.gz"
sha256 = "0588239cb534cd97b1d3900d0444311c119e45296a9f73f1ea81ea81a2cd3db1"
# dependency of pytest
options = ["!check"]
|
class Case :
def __init__(self,x,y):
self.id = str(x)+','+str(y)
self.x = x
self.y = y
self.piece = None
def check_case(self):
"""renvoie la piece si la case est occupé,renvoie -1 sinon """
if(self.piece != None):
return self.piece
return -1
def affecter_piece(self,piece):
self.piece = piece
self.piece.case_affectation(self)
def desaffecter_piece(self):
if self.piece != None :
self.piece = None
def show(self):
if self.piece != None and self.piece.case != None :
return "| "+str(self.piece.point)+" |"
else :
return "| 0 |"
def get_piece(self):
return self.piece
def get_x(self):
return self.x
def get_y(self):
return self.y
class Board :
def __init__(self,liste_case):
self.board = liste_case
def get_case(self,x,y):
for i in range(len(self.board)):
if self.board[i].x == x and self.board[i].y == y:
return self.board[i]
return -1
def show_board(self):
x = 0
s_board = ""
for case in self.board :
if case.x > x :
s_board += "\n"
x+=1
s_board += case.show()
print(s_board)
class Piece :
def __init__(self,name,color,point,board):
self.name = name
self.color = color
self.point = point
self.case = None
self.board = board
self.depla = []
def possible_depla(self):
"""calcule les déplacement actuellement possible sans contrainte externe, resultat dans depla"""
pass
def case_affectation(self,case):
self.case = case
def get_depla(self):
return self.depla
class Pion(Piece) :
def __init__(self,color,board):
super().__init__('Pion',color,1,board)
def possible_depla(self):
id_case = str(self.case.get_x())+','+str(self.case.get_y()+1)
id_case_2 = None
if self.case.get_y() == 2 :
id_case_2 = str(self.case.get_x())+','+str(self.case.get_y()+1)
for case in self.board.board:
if case.id == id_case and case.piece == None :
self.depla.append(case)
if id_case_2 != None and case.id == id_case_2 and case.piece == None:
self.depla.append(case)
class Roi(Piece):
def __init__(self,color,board):
super().__init__('Roi',color,1000,board)
class Dame(Piece) :
def __init__(self,color,board):
super().__init__('Dame',color,9,board)
|
class Solution:
def canPartition(self, nums: List[int]) -> bool:
dp, s = set([0]), sum(nums)
if s&1:
return False
for num in nums:
dp.update([v+num for v in dp if v+num <= s>>1])
return s>>1 in dp
|
class Solution:
def sortLinkedList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = head
curr = head.next
while curr:
if curr.val < 0:
prev.next = curr.next
curr.next = head
head = curr
curr = prev.next
else:
prev = curr
curr = curr.next
return head
|
def descuento(niños=int(input("Cuantos niños son "))):
if niños==2:
descuentoTotal=10
elif niños==3:
descuentoTotal=15
elif niños==4:
descuentoTotal=18
elif niños>=5:
descuentoTotal=18+(niños-4)*1
return print(descuentoTotal)
descuento()
|
"""Preprocessing Sample."""
__author__ = 'Devon Welcheck'
def preprocess(req, resp, resource, params): # pylint: disable=unused-argument
"""Preprocess skeleton."""
|
#Análise do relatório de vôos e viagens do aeroporto de Boston com base nos relatórios econômicos oficiais
with open('economic-indicators.csv', 'r') as boston:
total_voos = 0
maior = 0
total_passageiros = 0
maior_media_diaria = 0
ano_usuario = input('Qual ano deseja pesquisar?: ')
#Retornar o total de voos do arquivo
for linha in boston.readlines()[1:-1]:
lista = linha.split(',')
total_voos = total_voos + float(lista[3])
#Retornar o mês/ano com maior trânsito no aeroporto
if float(lista[2]) > float(maior):
maior = lista[2]
ano = lista[0]
mes = lista[1]
#Retorna o total de passageiros que transitaram no aeroporto no ano definido pelo usuário
if ano_usuario == lista[0]:
total_passageiros = total_passageiros + float(lista[2])
#Retorna o mês com maior média de diária de hotéis
if float(lista[5]) > float(maior_media_diaria):
maior_media_diaria = lista[5]
mes_maior_diaria = lista[1]
print('O total de voos é {}'.format(total_voos))
print('O mês/ano com maior trânsito no aeroporto foi {}/{}'.format(mes, ano))
print('O total de passageiros que passaram no ano de {} é {} passageiros'.format(str(ano_usuario),
str(total_passageiros)))
print('O mês do ano {} com maior média diária de hotel foi {}'.format(ano_usuario, mes_maior_diaria))
|
"""
Profile ../profile-datasets-py/div52/011.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div52/011.py"
self["Q"] = numpy.array([ 1.60776800e+00, 5.75602400e+00, 7.00189400e+00,
7.33717600e+00, 6.76175900e+00, 8.41951900e+00,
6.54641500e+00, 8.55272200e+00, 6.77920300e+00,
7.25516400e+00, 7.37081000e+00, 5.92257200e+00,
6.50599600e+00, 6.64283300e+00, 6.28100600e+00,
5.43963200e+00, 5.08957400e+00, 5.38038600e+00,
5.50633800e+00, 5.62897900e+00, 5.19042900e+00,
4.84112700e+00, 4.63224600e+00, 4.76220200e+00,
4.69470800e+00, 4.51451000e+00, 4.58671400e+00,
4.67290700e+00, 4.57081400e+00, 4.47585900e+00,
4.42605100e+00, 4.37786600e+00, 4.38445800e+00,
4.39293100e+00, 4.40466700e+00, 4.41761000e+00,
4.37084000e+00, 4.20133400e+00, 4.03640900e+00,
3.99758200e+00, 3.97225900e+00, 3.89513500e+00,
3.76079000e+00, 3.63594700e+00, 3.81527700e+00,
3.99037900e+00, 4.23041800e+00, 4.51608500e+00,
4.76413100e+00, 4.79784600e+00, 4.83083700e+00,
6.93679600e+00, 9.88992600e+00, 1.41402000e+01,
2.17185200e+01, 2.91457900e+01, 3.96929600e+01,
5.04349000e+01, 6.08671100e+01, 7.10095300e+01,
8.43479200e+01, 1.11923300e+02, 1.38998100e+02,
1.94360100e+02, 2.52783000e+02, 3.20280200e+02,
3.93544100e+02, 4.69894600e+02, 5.53426000e+02,
6.41501600e+02, 7.71092500e+02, 8.98548200e+02,
1.06642900e+03, 1.23389900e+03, 1.45307300e+03,
1.68006300e+03, 2.07637800e+03, 2.51954400e+03,
3.27713300e+03, 4.12034400e+03, 5.07040900e+03,
6.02835400e+03, 6.34354100e+03, 6.44987700e+03,
5.89160400e+03, 5.06925600e+03, 4.04401800e+03,
3.04533400e+03, 2.16305800e+03, 1.42927300e+03,
9.42830700e+02, 8.61332300e+02, 9.09295200e+02,
1.23575300e+03, 1.77325600e+03, 3.36407200e+03,
5.26097100e+03, 5.71855000e+03, 5.98901400e+03,
5.82855400e+03, 5.67443100e+03])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56504000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61259000e+01, 6.09895000e+01, 6.61252000e+01,
7.15398000e+01, 7.72395000e+01, 8.32310000e+01,
8.95203000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17777000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23441000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90892000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53627000e+02, 7.77789000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31523000e+02, 9.58591000e+02,
9.86066000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 311.3895, 311.3882, 311.3878, 311.3877, 311.3879, 311.3874,
311.388 , 311.3873, 311.3879, 311.3877, 311.3877, 311.3882,
311.388 , 311.3879, 311.388 , 311.3883, 311.3884, 311.3883,
311.3883, 311.3882, 311.3884, 311.3885, 311.3886, 311.3885,
311.3885, 311.3886, 311.3886, 311.3885, 311.3886, 311.3886,
311.3886, 311.3886, 311.3886, 311.3886, 311.3886, 311.3886,
311.3886, 311.3887, 311.3887, 311.3888, 311.3888, 311.3888,
311.8368, 312.3079, 312.7998, 313.3147, 313.8527, 314.4136,
314.9985, 315.6075, 316.2405, 316.8978, 317.5809, 318.2885,
319.0201, 319.7787, 320.5633, 321.3738, 321.3704, 321.3672,
321.3629, 321.354 , 321.3453, 321.3275, 321.3088, 321.2871,
321.2635, 321.239 , 321.2121, 321.1838, 321.1422, 321.1012,
321.0473, 320.9934, 320.923 , 320.85 , 320.7227, 320.5802,
320.3368, 320.0658, 319.7604, 319.4525, 319.3512, 319.3171,
319.4965, 319.7608, 320.0903, 320.4113, 320.6948, 320.9306,
321.087 , 321.1132, 321.0978, 320.9928, 320.8201, 320.3088,
319.6992, 319.5521, 319.4652, 319.5168, 319.5663])
self["T"] = numpy.array([ 170.672, 167.1 , 177.713, 195.506, 207.725, 218.427,
235.452, 261.271, 286.139, 302.526, 307.761, 299.105,
277.321, 254.123, 242.604, 242.111, 244.188, 247.235,
249.79 , 251.021, 249.495, 247.35 , 245.156, 243.382,
241.117, 238.603, 237.177, 235.891, 234.271, 232.728,
231.48 , 230.272, 230.403, 230.58 , 230.857, 231.173,
231.319, 231.125, 230.936, 230.468, 229.983, 229.041,
227.593, 226.199, 225.705, 225.223, 225.188, 225.476,
225.743, 225.913, 226.079, 225.665, 225.013, 224.05 ,
222.293, 220.571, 219.676, 218.897, 218.878, 219.527,
220.435, 222.487, 224.501, 226.873, 229.258, 231.594,
233.885, 236.173, 238.493, 240.796, 243.218, 245.601,
248.126, 250.621, 253.108, 255.562, 257.808, 259.968,
261.977, 263.921, 265.771, 267.581, 269.295, 270.928,
272.357, 273.557, 274.577, 275.147, 275.554, 275.814,
276.066, 276.464, 277.23 , 278.183, 278.559, 276.474,
273.474, 274.53 , 274.81 , 274.81 , 274.81 ])
self["O3"] = numpy.array([ 0.2033725 , 0.2424187 , 0.3208637 , 0.4562969 , 0.736027 ,
1.047125 , 1.27765 , 1.424369 , 1.592244 , 1.945423 ,
2.494494 , 3.276502 , 4.362954 , 5.659009 , 6.054292 ,
6.016611 , 5.807721 , 5.465095 , 5.068172 , 4.685214 ,
4.427215 , 4.293835 , 4.20855 , 4.135007 , 4.034985 ,
3.921192 , 3.781656 , 3.644418 , 3.521658 , 3.404957 ,
3.31342 , 3.224845 , 3.115542 , 3.008671 , 2.838926 ,
2.645074 , 2.436685 , 2.192161 , 1.954276 , 1.756302 ,
1.566934 , 1.406719 , 1.277961 , 1.153048 , 1.06527 ,
0.9795561 , 0.90675 , 0.8436835 , 0.7768094 , 0.6765951 ,
0.5785423 , 0.4980748 , 0.4259511 , 0.3548743 , 0.284146 ,
0.2148278 , 0.170396 , 0.1296997 , 0.09665075, 0.07037028,
0.04774848, 0.0390997 , 0.03060822, 0.02923244, 0.02885916,
0.02934259, 0.03040131, 0.03152678, 0.03279865, 0.03412979,
0.03602205, 0.0378829 , 0.03856705, 0.03917781, 0.03968628,
0.04016728, 0.04066729, 0.04116737, 0.04188355, 0.04265563,
0.04372776, 0.04484095, 0.0448461 , 0.04464854, 0.0438066 ,
0.04338835, 0.04330029, 0.04399183, 0.04493602, 0.0461 ,
0.04719323, 0.04845931, 0.05025693, 0.05333931, 0.05646073,
0.05959075, 0.06483308, 0.05655864, 0.0507791 , 0.05078729,
0.05079517])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 274.81
self["S2M"]["Q"] = 6138.87608117
self["S2M"]["O"] = 0.0507714396589
self["S2M"]["P"] = 1016.79
self["S2M"]["U"] = 8.31799
self["S2M"]["V"] = -1.2184
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 1
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 272.988
self["SKIN"]["SALINITY"] = 35.0
self["SKIN"]["FOAM_FRACTION"] = 0.0
self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3])
self["ZENANGLE"] = 0.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = 80.1708
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([1992, 7, 15])
self["TIME"] = numpy.array([18, 0, 0])
|
class Pessoa: #substantivo
def __init__(self, nome: str, idade: int) -> None:
self.nome = nome #substantivo
self.idade = idade #substantivo
def dirigir(self, veiculo: str) -> None: #verbos
print(f'Dirigindo um(a) {veiculo}')
def cantar(self) -> None: #verbos
print('lalalala')
def apresentar_idade(self) -> int: #verbos
return self.idade
|
"""
[2016-07-22] Challenge #276 [Hard] ∞ Loop solver part 2
https://www.reddit.com/r/dailyprogrammer/comments/4u3e96/20160722_challenge_276_hard_loop_solver_part_2/
This is the same challenge as /u/jnazario's excellent [∞ Loop
solver](https://www.reddit.com/r/dailyprogrammer/comments/4rug59/20160708_challenge_274_hard_loop_solver/) but for
larger inputs.
The input format is different, as you will be given a presolved partial grid, where each cell is the possible rotations
that line up with a possible rotation of neighbour cells.
The challenge is to find ALL of the valid grid solutions
# 20x20 input visualization
┌─┬─────┬────┬───────┬────┬───┬───┬────┬─────┬────────┬────┬────────┬────┬─────┬──┬──┬──┬──┬──┬──┐
│6│12 │6 │10 │10 │12 │6 │12 │6 │12 │6 │14 │12 │6 │10│10│10│14│14│12│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│13 │3 │14 │12 │3 │9 │7 │15 │9 │5 │7 │11 │9 │6 │12│6 │13│5 │5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│9 │6 │9 │7 │10 │10 │9 │7 │10 │13 │7 │10 │10 │9 │5 │5 │5 │3 │9 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│5│6 │15 │12 │5 │6 │14 │14 │15 │12 │5 │3 │10 │14 │10│11│11│15│10│12│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│13 │3 │9 │3 │15 │11 │13 │7 │9 │7 │12 │6 │11 │10│10│10│9 │6 │9 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│11 │14 │14 │14 │9 │6 │15 │15 │12 │5 │3 │15 │14 │14│12│6 │12│3 │12│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│5│6 │9 │3 │9 │6 │9 │5 │7 │13 │5 │6 │15 │15 │15│13│7 │13│6 │13│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│5│5 │6 │10 │10 │13 │6 │15 │15 │11 13 │13 7│7 13 11 │11 7│11 │15│11│9 │3 │15│9 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│9 │5 │6 │10 │11 │9 │7 │9 │6 3 │11 │11 13 14│14 7│10 │11│14│12│6 │15│12│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│5│6 │9 │3 │12 │6 │10 │9 │6 │13 11 14│6 12│14 7 │9 │6 │10│9 │7 │9 │5 │5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│11 │14 │10 │9 │7 │10 │14 │13 11│7 14 │11 │11 │10 │13 │6 │14│9 │6 │13│5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│12 │7 │12 │6 │13 │6 │9 │3 6 │13 │6 │10 │12 │7 │11│11│14│15│13│5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│13 11│3 9 │11 13 7│13 7│3 9│9 3│6 12│14 7 │15 │11 │10 │9 │3 │14│10│9 │3 │9 │5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│13 14│6 12│14 7 │11 │12 │6 │13 │5 │3 │14 │12 │6 │12 │5 │6 │14│14│12│5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│5│3 │15 │11 │12 │7 │9 │7 │11 │12 │5 │7 │9 │7 │15│11│13│7 │13│5 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│5│6 │9 │6 │11 │13 │6 │13 │6 │15 │9 │7 │10 │13 │3 │10│9 │3 │15│13│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│3│13 │6 │15 │12 │7 │15 │9 │3 │13 │6 │13 11 │6 12│11 7 │14│10│12│6 │15│9 │
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│6│13 │3 │11 │15 │15 │13 │6 │10 │15 │11 │11 14 │11 │14 11│13│6 │15│9 │3 │12│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│7│11 │12 │6 │15 │9 │5 │7 │14 │9 │6 │14 13 │12 6│7 14 │9 │5 │7 │12│6 │13│
├─┼─────┼────┼───────┼────┼───┼───┼────┼─────┼────────┼────┼────────┼────┼─────┼──┼──┼──┼──┼──┼──┤
│3│10 │9 │3 │11 │10 │11 │11 │11 │10 │9 │3 │11 │11 │10│11│11│9 │3 │9 │
└─┴─────┴────┴───────┴────┴───┴───┴────┴─────┴────────┴────┴────────┴────┴─────┴──┴──┴──┴──┴──┴──┘
1. The numbers in each cell are indexes (0-based) into the looper tiles `╹╺┗╻┃┏┣╸┛━┻┓┫┳╋` (leading index 0 is space)
2. The 4 digit binary representation of each index indicates whether there is a tick that points `WSEN`
3. Cells with a single index are forced moves. Cells with multiple indexes are potential moves.
4. The general strategy for finding all valid final (ones with single indexes per cell) grids is to repeatedly split
the grid based on one multiple cell (where each grid has a unique index in that cell), and then find all forced moves
in each independent grid.
5. A forced move by row is one where the left cells' East tick is equal to the right cell's West tick. By column, the
top cell's South tick is equal to the lower cell's North tick.
**input** (each row separated by LF, each cell by comma, each candidate by space)
20x20
6,12,6,10,10,12,6,12,6,12,6,14,12,6,10,10,10,14,14,12
7,13,3,14,12,3,9,7,15,9,5,7,11,9,6,12,6,13,5,5
7,9,6,9,7,10,10,9,7,10,13,7,10,10,9,5,5,5,3,9
5,6,15,12,5,6,14,14,15,12,5,3,10,14,10,11,11,15,10,12
7,13,3,9,3,15,11,13,7,9,7,12,6,11,10,10,10,9,6,9
7,11,14,14,14,9,6,15,15,12,5,3,15,14,14,12,6,12,3,12
5,6,9,3,9,6,9,5,7,13,5,6,15,15,15,13,7,13,6,13
5,5,6,10,10,13,6,15,15,11 13,13 7,7 13 11,11 7,11,15,11,9,3,15,9
7,9,5,6,10,11,9,7,9,6 3,11,11 13 14,14 7,10,11,14,12,6,15,12
5,6,9,3,12,6,10,9,6,13 11 14,6 12,14 7,9,6,10,9,7,9,5,5
7,11,14,10,9,7,10,14,13 11,7 14,11,11,10,13,6,14,9,6,13,5
7,12,7,12,6,13,6,9,3 6,13,6,10,12,7,11,11,14,15,13,5
7,13 11,3 9,11 13 7,13 7,3 9,9 3,6 12,14 7,15,11,10,9,3,14,10,9,3,9,5
7,13 14,6 12,14 7,11,12,6,13,5,3,14,12,6,12,5,6,14,14,12,5
5,3,15,11,12,7,9,7,11,12,5,7,9,7,15,11,13,7,13,5
5,6,9,6,11,13,6,13,6,15,9,7,10,13,3,10,9,3,15,13
3,13,6,15,12,7,15,9,3,13,6,13 11,6 12,11 7,14,10,12,6,15,9
6,13,3,11,15,15,13,6,10,15,11,11 14,11,14 11,13,6,15,9,3,12
7,11,12,6,15,9,5,7,14,9,6,14 13,12 6,7 14,9,5,7,12,6,13
3,10,9,3,11,10,11,11,11,10,9,3,11,11,10,11,11,9,3,9
**output**
to save space just provide the number of distinct valid grids. (I get 12)
# 30x30 challenges
thanks to /u/bearific for creating a generator for this challenge. The above and larger inputs are available here:
https://gist.github.com/FrankRuis/0aa761b9562a32ea7fdcff32f1768eb0
"reduced input" (above) formats of the 30x30 challenges: (you may use the original input format and solve these anyway
you like)
**first input**
6,10,14,12,6,14,10,12,6,12,6,14,10,12,6,10,14,14,14,12,6,14,12,6,10,14,10,12,6,12
3,14,13,7,13,3,14,15,15,15,11,13,6,9,5,6,11,9,5,3,15,15,13,5,6,15,10,15,13,5
6,11,15,15,15,10,13 11,7 11,15,9,6,9,7,12,3,13,6,10,11,14,11,15,15,11,15,9,6,13,7,13
7,12,3,13,5,6,13 14,7 14,11,14,9,6,15,11,14,15,11,10,12,7,12,7,13 11,6 12,13 7,6 12,11 7,13,5,5
7,11,14,9,3,9,7,13,6,15,14,13,5,6,9,3,10,10,13,3,15,13,3 6,15,15,11 13,14 7,13,5,5
7,14,13,6,14,12,5,7,15,15,9,3,9,5,6,12,6,14,9,6,15,13 11,6 12 3 9,9 3,7 13,14 7,15,13,7,9
7,15,13,5,5,3,9,5,5,5,6,14,14,9,3,11,11,13,6,15,15,13 14,7 11 14,14,15,15,15,11,11,12
7,11,9,5,7,12,6,13,3,13,3,13,3,10,10,10,14,11 7,9,5,3,11,13 14,7 11,15,11,11,10,12,5
5,6,10,9,5,5,5,7,12,5,6,9,6,12,6,14,13 11,6 12 3 9,12 6,7 13,12 6,6 12,9 3,7 14,15,10,12,6,15,13
7,9,6,12,3,9,5,5,3,9,3,14,11 13,11 13 7,11 13 7,13 11 7,5 10,7 13 14,11 7,13,5,7,14,11,9,6,11,13,3,13
5,6,11,9,6,12,3,13,6,14,14,13,6,10,14 11,11,11 14,13,6 3,15,11,15,9,6,12,7,10,9,6,13
3,11,10,10,9,3,10,15,9,7,15,13,5,6,13 14,6 12,14 13 7,9 3,7 13 14,11 7,14,9,6,11,13,3,12,6,11,9
6,10,14,10,10,12,6,15,10,11 13,13 7,7 11,13,5,5,3,11,14,13,6 3,15,12,5,6,15,12,5,7,14,12
5,6,9,6,14,11,15,15,10,12 9,7,11 14,13,7,13,6,12,5,3,11 14,9,5,5,7,15,15,11,15,15,9
3,15,14,15,13,6,9,5,6,13 11 14,3 9,14 13 7,13 7,3 9,11 7,11,15,9,6,14 11,10,11,15,11 13,11 7,13,6,11,11,12
6,15,15,15,11,15,14,11 13,13 7,7 14,12,3,15,10,12 9,6,9,6,11 13,11 7 14,10,12,3,14 13,14 7,15,11,12,6,13
3,9,7,9,6,13 11,7 13 11,14 11 7,15,11,15,12,5,6,13 14,3 9,12 6,3 9,10 5,14 11 7,10,15,14,13,5,3,10,15,11,13
6,14,11,14,15,13 11 14,7 13 11 14,11 13 7 14,11 7,10,9,3,11,13,5,6,13,6,12 9,3 6,10,13,3,13,5,6,12,3,10,9
3,13,6,13,3,13 14,7 13 14,14 13 11 7,14 11 7,14,12,6,10,9,5,5,3,15,11 13 14,14 7,10,13,6,15,11,13,5,6,10,12
6,15,9,3,14,9,7,13 14,7 14,15,11,11,10,12,3,15,12,3,14 13,9 3,6 12,11 7,13,7,10,11,11,15,12,5
7,13,6,10,15,14,9,5,3,11,14,12,6,9,6,9,3,14,9,6,15,12 9,5,7,10,10,12,3,13,5
7,9,7,14,11,11,12,5,6,10,11,13,7,12,5,6,12,7,10,11,13 11,3 9 6 12,13 11 7,7 11,14,14,11,12,5,5
5,6,13,7,12,6,13,5,3,14,14,13,3,15,11,11,11,13,6,12,7 13 14,10 5,11 7 14,9 12,3,15,14,11,11,13
7,9,7,9,5,7,11,15,14,13,5,7,12,3,10,14,12,3,13 11,3 9,9 3,6 12 3 9,14 13 7,14 7,10,11,15,14,12,5
7,12,3,10,11,15,14,11,9,3,9,3,15,12,6,13,3,10,13 14,6 12,12 6,7 14,11,15,14,12,3,13,5,5
3,9,6,10,12,7,9,6,14,10,12,6,13,7,15,15,12,6,9,7,15,11,12,3,13,3,12,3,9,5
6,12,7,14,9,7,14,9,7,12,3,9,3,15,11 13,11 7,9,5,6,15,15,14,15,12,3,14,13,6,14,9
7,15,13,7,10,11,11,10,13,5,6,10,14,13,6 3,14 11,10,9,5,5,3,13,5,5,6,15,11,15,15,12
7,9,3,13,6,14,12,6,15,11,11,10,11,11,13 14,7 14,14,12,7,15,12,7,15,13,3,13,6,11,15,13
3,10,10,9,3,9,3,9,3,10,10,10,10,10,9,3,9,3,9,3,11,9,3,11,10,9,3,10,11,9
**input 2**
6,10,14,12,6,14,10,12,6,12,6,14,10,12,6,10,14,14,14,12,6,14,12,6,10,14,10,12,6,12
3,14,13,7,13,3,14,15,15,15,11,13,6,9,5,6,11,9,5,3,15,15,13,5,6,15,10,15,13,5
6,11,15,15,15,10,13 11,7 11,15,9,6,9,7,12,3,13,6,10,11,14,11,15,15,11,15,9,6,13,7,13
7,12,3,13,5,6,13 14,7 14,11,14,9,6,15,11,14,15,11,10,12,7,12,7,13 11,6 12,13 7,6 12,11 7,13,5,5
7,11,14,9,3,9,7,13,6,15,14,13,5,6,9,3,10,10,13,3,15,13,3 6,15,15,13 11,14 7,13,5,5
7,14,13,6,14,12,5,7,15,15,9,3,9,5,6,12,6,14,9,6,15,11 13,12 6 9 3,3 9,13 7,7 14,15,13,7,9
7,15,13,5,5,3,9,5,5,5,6,14,14,9,3,11,11,13,6,15,15,14 13,11 7 14,14,15,15,15,11,11,12
7,11,9,5,7,12,6,13,3,13,3,13,3,10,10,10,14,11 7,9,5,3,11,14 13,11 7,15,11,11,10,12,5
5,6,10,9,5,5,5,7,12,5,6,9,6,12,6,14,13 11,6 12 3 9,12 6,7 13,12 6,6 12,9 3,14 7,15,10,12,6,15,13
7,9,6,12,3,9,5,5,3,9,3,14,13 11,7 13 11,13 11 7,7 13 11,5 10,13 7 14,7 11,13,5,7,14,11,9,6,11,13,3,13
5,6,11,9,6,12,3,13,6,14,14,13,6,10,11 14,11,11 14,13,6 3,15,11,15,9,6,12,7,10,9,6,13
3,11,10,10,9,3,10,15,9,7,15,13,5,6,14 13,12 6,14 7 13,9 3,7 13 14,11 7,14,9,6,11,13,3,12,6,11,9
6,10,14,10,10,12,6,15,10,13 11,7 13,11 7,13,5,5,3,11,14,13,6 3,15,12,5,6,15,12,5,7,14,12
5,6,9,6,14,11,15,15,10,9 12,7,14 11,13,7,13,6,12,5,3,11 14,9,5,5,7,15,15,11,15,15,9
3,15,14,15,13,6,9,5,6,14 13 11,9 3,7 13 14,13 7,3 9,11 7,11,15,9,6,14 11,10,11,15,13 11,7 11,13,6,11,11,12
6,15,15,15,11,15,14,13 11,7 13,7 14,12,3,15,10,12 9,6,9,6,13 11,7 11 14,10,12,3,13 14,7 14,15,11,12,6,13
3,9,7,9,6,13 11,7 13 11,11 7 14,15,11,15,12,5,6,13 14,9 3,6 12,9 3,5 10,7 11 14,10,15,14,13,5,3,10,15,11,13
6,14,11,14,15,13 11 14,7 13 11 14,14 13 11 7,11 7,10,9,3,11,13,5,6,13,6,9 12,3 6,10,13,3,13,5,6,12,3,10,9
3,13,6,13,3,13 14,7 13 14,13 11 7 14,14 7 11,14,12,6,10,9,5,5,3,15,14 13 11,14 7,10,13,6,15,11,13,5,6,10,12
6,15,9,3,14,9,7,13 14,7 14,15,11,11,10,12,3,15,12,3,13 14,3 9,12 6,7 11,13,7,10,11,11,15,12,5
7,13,6,10,15,14,9,5,3,11,14,12,6,9,6,9,3,14,9,6,15,9 12,5,7,10,10,12,3,13,5
7,9,7,14,11,11,12,5,6,10,11,13,7,12,5,6,12,7,10,11,11 13,12 6 9 3,7 13 11,11 7,14,14,11,12,5,5
5,6,13,7,12,6,13,5,3,14,14,13,3,15,11,11,11,13,6,12,14 13 7,5 10,11 7 14,12 9,3,15,14,11,11,13
7,9,7,9,5,7,11,15,14,13,5,7,12,3,10,14,12,3,13 11,3 9,9 3,3 9 6 12,14 13 7,7 14,10,11,15,14,12,5
7,12,3,10,11,15,14,11,9,3,9,3,15,12,6,13,3,10,13 14,6 12,12 6,14 7,11,15,14,12,3,13,5,5
3,9,6,10,12,7,9,6,14,10,12,6,13,7,15,15,12,6,9,7,15,11,12,3,13,3,12,3,9,5
6,12,7,14,9,7,14,9,7,12,3,9,3,15,13 11,7 11,9,5,6,15,15,14,15,12,3,14,13,6,14,9
7,15,13,7,10,11,11,10,13,5,6,10,14,13,3 6,11 14,10,9,5,5,3,13,5,5,6,15,11,15,15,12
7,9,3,13,6,14,12,6,15,11,11,10,11,11,14 13,14 7,14,12,7,15,12,7,15,13,3,13,6,11,15,13
3,10,10,9,3,9,3,9,3,10,10,10,10,10,9,3,9,3,9,3,11,9,3,11,10,9,3,10,11,9
"""
def main():
pass
if __name__ == "__main__":
main()
|
'''Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
Ex: n = leiaInt('Digite um n: ')'''
def leiaInt(msg):
ok = False
valor = 0
while True:
n = str(input(msg))
if n.isnumeric():
valor = int(n)
ok = True
else:
print(f'''\033[0;31m
ERRO! Você digitou "{n}".
Digite um número inteiro válido.\033[m''')
print()
if ok:
break
return valor
#programa
print('---'*10)
n = leiaInt('Digite um número: ')
print(f'Você digitou o número {n}.')
print('---'*10) |
API_GROUPS = {
'authentication': ['/api-auth/', '/api/auth-valimo/',],
'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',],
'organization': [
'/api/customers/',
'/api/customer-permissions-log/',
'/api/customer-permissions-reviews/',
'/api/customer-permissions/',
],
'marketplace': [
'/api/marketplace-bookings/',
'/api/marketplace-cart-items/',
'/api/marketplace-categories/',
'/api/marketplace-category-component-usages/',
'/api/marketplace-checklists-categories/',
'/api/marketplace-checklists/',
'/api/marketplace-component-usages/',
'/api/marketplace-offering-files/',
'/api/marketplace-offerings/',
'/api/marketplace-order-items/',
'/api/marketplace-orders/',
'/api/marketplace-plans/',
'/api/marketplace-plugins/',
'/api/marketplace-public-api/',
'/api/marketplace-resource-offerings/',
'/api/marketplace-resources/',
'/api/marketplace-screenshots/',
'/api/marketplace-service-providers/',
],
'reporting': [
'/api/support-feedback-average-report/',
'/api/support-feedback-report/',
],
}
|
# -*- coding: utf-8 -*-
"""Module compliance_suite.functions.update_server_settings.py
Functions to update server config/settings based on the response of a previous
API request. Each function should accept a Runner object and modify its
"retrieved_server_settings" attribute
"""
def update_supported_filters(runner, resource, response_obj):
"""Update server settings with the supported filters for a resource
Arguments:
runner (Runner): reference to Runner object
resource (str): identifies project, study, expression, continuous
response_obj (Response): response object to parse
"""
for filter_obj in response_obj:
runner.retrieved_server_settings[resource]["supp_filters"]\
.append(filter_obj["filter"])
def update_expected_format(runner, resource, response_obj):
"""Update server settings with the expected file format for a resource
Arguments:
runner (Runner): reference to Runner object
resource (str): identifies project, study, expression, continuous
response_obj (Response): response object to parse
"""
format_str = response_obj["fileType"]
runner.retrieved_server_settings["expressions"]["exp_format"] = format_str
runner.retrieved_server_settings["continuous"]["exp_format"] = format_str
|
df = pd.read_csv(DATA)
df = df.sample(frac=1.0)
df.reset_index(drop=True, inplace=True)
result = df.tail(n=10)
|
def to_binary(number):
binarynumber=""
if (number!=0):
while (number>=1):
if (number %2==0):
binarynumber=binarynumber+"0"
number=number/2
else:
binarynumber=binarynumber+"1"
number=(number-1)/2
else:
binarynumber="0"
return "".join(reversed(binarynumber))
if __name__ == '__main__':
print(to_binary(35))
print("\n")
print(bin(35)) |
x = 5
y = 3
z = x + y
print(x)
print(y)
print(x + y)
print(z)
w = z
print(w) |
#Calculadora de tabuada
n = int(input('Deseja ver tabuada de que numero?'))
for c in range(1, 13):
print('{} X {:2}= {} '. format(n, c, n * c))
|
COLUMNS = [
'tipo_registro',
'nro_pv_matriz',
'vl_total_bruto',
'qtde_cvnsu',
'vl_total_rejeitado',
'vl_total_rotativo',
'vl_total_parcelado_sem_juros',
'vl_total_parcelado_iata',
'vl_total_dolar',
'vl_total_desconto',
'vl_total_liquido',
'vl_total_gorjeta',
'vl_total_tx_embarque',
'qtde_cvnsu_acatados'
] |
# Ask user to enter their country name.
# print out their phone code.
l_country_phone_code = ["China","86","Germany","49","Turkey","90"]
def country_name_to_phone_code_list(country_name):
for index in range(len(l_country_phone_code)):
if l_country_phone_code[index] == country_name:
return l_country_phone_code[index+1]
def country_name_to_phone_code_dict(country_name):
pass
print(country_name_to_phone_code_list("Turkey"))
print(country_name_to_phone_code_list("Germany"))
print(country_name_to_phone_code_list("China")) |
"""
EGF string variables for testing.
"""
# POINT
valid_pt = """PT
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
"""
invalid_pt_geom = """PTs
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
"""
invalid_pt_last_line_1 = """PT
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
"""
invalid_pt_last_line_2 = """PT
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
a
"""
invalid_pt_coord_sets = """PT
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
42.355465, -71.066412, 10.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
"""
invalid_pt_headers = """PT
Park Name, City, Pond, Fountain
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
"""
invalid_pt_sections = """PT
Park Name, City, Pond, Fountain
"""
invalid_pt_section_separators = """PT
Park Name, City, Pond, Fountain
Post office Square, Boston, FALSE, TRUE
42.356243, -71.055631, 2.0
Boston Common, Boston, TRUE, TRUE
42.355465, -71.066412, 10.0
"""
# LINESTRING
valid_ls = """LS
Park Name, Feature Description
Post Office Square, A walk by the fountain
42.356716, -71.055685, 0.0
42.356587, -71.055769, 0.0
42.356566, -71.055754, 0.0
42.356539, -71.055746, 0.0
42.356511, -71.055757, 0.0
42.356495, -71.05579, 0.0
42.356485, -71.05583, 0.0
42.356389, -71.055842, 0.0
42.356252, -71.055796, 0.0
42.356046, -71.055642, 0.0
42.355876, -71.055697, 0.0
42.355828, -71.055758, 0.0
Boston Common, A walk by the fountain
42.356251, -71.062737, 0.0
42.35621, -71.063012, 0.0
42.356153, -71.06305, 0.0
42.356144, -71.063115, 0.0
42.356136, -71.063261, 0.0
42.355825, -71.064018, 0.0
"""
invalid_ls_coord_sets_1 = """LS
Park Name, Feature Description
Post Office Square, A walk by the fountain
42.356716, -71.055685, 0.0
42.356587, -71.055769, 0.0
42.356566, -71.055754, 0.0
42.356539, -71.055746, 0.0
42.356511, -71.055757, 0.0
42.356495, -71.05579, 0.0
42.356485, -71.05583, 0.0
42.356389, -71.055842, 0.0
42.356252, -71.055796, 0.0
42.356046, -71.055642, 0.0
42.355876, -71.055697, 0.0
42.355828, -71.055758, 0.0
Boston Common, A walk by the fountain
42.356251, -71.062737, 0.0
"""
invalid_ls_coord_sets_2 = """LS
Park Name, Feature Description
Post Office Square, A walk by the fountain
42.356716, -71.055685, 0.0
42.356587, -71.055769, 0.0
42.356566, -71.055754, 0.0
42.356539, -71.055746, 0.0
42.356511, -71.055757, 0.0
42.356495, -71.05579, 0.0
42.356485, -71.05583, 0.0
42.356389, -71.055842, 0.0
42.356252, -71.055796, 0.0
42.356046, -71.055642, 0.0
42.355876, -71.055697, 0.0
42.355828, -71.055758, 0.0
Boston Common, A walk by the fountain
42.356251, -71.062737, 0.0
42.35621, -71.063012, 0.0
42.356153, -71.06305, 0.0
42.356144, -71.063115, 0.0
42.356136, -71.063261, 0.0
42.355825, -71.064018, 0.0
"""
invalid_ls_sections = """LS
Park Name, Feature Description
Post Office Square, A walk by the fountain
42.356716, -71.055685, 0.0
42.356587, -71.055769, 0.0
42.356566, -71.055754, 0.0
42.356539, -71.055746, 0.0
42.356511, -71.055757, 0.0
42.356495, -71.05579, 0.0
42.356485, -71.05583, 0.0
42.356389, -71.055842, 0.0
42.356252, -71.055796, 0.0
42.356046, -71.055642, 0.0
42.355876, -71.055697, 0.0
42.355828, -71.055758, 0.0
Boston Common, A walk by the fountain
42.356251, -71.062737, 0.0
42.35621, -71.063012, 0.0
42.356153, -71.06305, 0.0
42.356144, -71.063115, 0.0
42.356136, -71.063261, 0.0
42.355825, -71.064018, 0.0
"""
# POLYGON
valid_poly = """POLY
Park Name, Feature Description
Post Office Square, Boundary of Post Office Square with holes for buildings
42.356856, -71.055757, 0.0
42.35608, -71.054976, 0.0
42.355697, -71.055636, 0.0
42.356003, -71.055941, 0.0
42.356767, -71.05622, 0.0
42.355955, -71.055522, 0.0
42.355894, -71.055458, 0.0
42.355846, -71.055546, 0.0
42.355908, -71.055615, 0.0
42.356089, -71.055312, 0.0
42.356005, -71.055226, 0.0
42.355969, -71.055288, 0.0
42.356058, -71.055373, 0.0
Boston Common, Boundary of Boston Common with a hole for the Frog Pond
42.356514, -71.062157, 0.0
42.355222, -71.063337, 0.0
42.352457, -71.064638, 0.0
42.352639, -71.067238, 0.0
42.356132, -71.06915, 0.0
42.357591, -71.06326, 0.0
42.356047, -71.065045, 0.0
42.355953, -71.065107, 0.0
42.355911, -71.065249, 0.0
42.356018, -71.065909, 0.0
42.35601, -71.066016, 0.0
42.355918, -71.066198, 0.0
42.355854, -71.066417, 0.0
42.355876, -71.066521, 0.0
42.355938, -71.066564, 0.0
42.355985, -71.066547, 0.0
42.356221, -71.066, 0.0
42.356296, -71.065647, 0.0
42.35627, -71.065341, 0.0
42.356186, -71.065127, 0.0
42.356123, -71.065061, 0.0
"""
invalid_poly_coord_sets_1 = """POLY
Park Name, Feature Description
Post Office Square, Boundary of Post Office Square with holes for buildings
42.356856, -71.055757, 0.0
42.35608, -71.054976, 0.0
42.355697, -71.055636, 0.0
42.356003, -71.055941, 0.0
42.356767, -71.05622, 0.0
42.356856, -71.055757, 0.0
42.355955, -71.055522, 0.0
42.355894, -71.055458, 0.0
42.355846, -71.055546, 0.0
42.355908, -71.055615, 0.0
42.355955, -71.055522, 0.0
42.356089, -71.055312, 0.0
42.356005, -71.055226, 0.0
42.355969, -71.055288, 0.0
42.356058, -71.055373, 0.0
42.356089, -71.055312, 0.0
Boston Common, Boundary of Boston Common with a hole for the Frog Pond
42.356514, -71.062157, 0.0
42.355222, -71.063337, 0.0
42.356047, -71.065045, 0.0
42.355953, -71.065107, 0.0
42.355911, -71.065249, 0.0
42.356018, -71.065909, 0.0
42.35601, -71.066016, 0.0
42.355918, -71.066198, 0.0
42.355854, -71.066417, 0.0
42.355876, -71.066521, 0.0
42.355938, -71.066564, 0.0
42.355985, -71.066547, 0.0
42.356221, -71.066, 0.0
42.356296, -71.065647, 0.0
42.35627, -71.065341, 0.0
42.356186, -71.065127, 0.0
42.356123, -71.065061, 0.0
42.356047, -71.065045, 0.0
"""
invalid_poly_coord_sets_2 = """POLY
Park Name, Feature Description
Post Office Square, Boundary of Post Office Square with holes for buildings
42.356856, -71.055757, 0.0
42.35608, -71.054976, 0.0
42.355697, -71.055636, 0.0
42.356003, -71.055941, 0.0
42.356767, -71.05622, 0.0
42.356856, -71.055757, 0.0
42.355955, -71.055522, 0.0
42.355894, -71.055458, 0.0
42.355846, -71.055546, 0.0
42.355908, -71.055615, 0.0
42.355955, -71.055522, 0.0
42.356089, -71.055312, 0.0
42.356005, -71.055226, 0.0
42.355969, -71.055288, 0.0
42.356058, -71.055373, 0.0
42.356089, -71.055312, 0.0
Boston Common, Boundary of Boston Common with a hole for the Frog Pond
42.356514, -71.062157, 0.0
42.355222, -71.063337, 0.0
42.352457, -71.064638, 0.0
42.352639, -71.067238, 0.0
42.356132, -71.06915, 0.0
42.357591, -71.06326, 0.0
42.356514, -71.062157, 0.0
42.356047, -71.065045, 0.0
42.355953, -71.065107, 0.0
42.355911, -71.065249, 0.0
42.356018, -71.065909, 0.0
42.35601, -71.066016, 0.0
42.355918, -71.066198, 0.0
42.355854, -71.066417, 0.0
42.355876, -71.066521, 0.0
42.355938, -71.066564, 0.0
42.355985, -71.066547, 0.0
42.356221, -71.066, 0.0
42.356296, -71.065647, 0.0
42.35627, -71.065341, 0.0
42.356186, -71.065127, 0.0
42.356123, -71.065061, 0.0
42.356047, -71.065045, 0.0
""" |
class GuidAttribute(Attribute,_Attribute):
"""
Supplies an explicit System.Guid when an automatic GUID is undesirable.
GuidAttribute(guid: str)
"""
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,guid):
""" __new__(cls: type,guid: str) """
pass
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the System.Guid of the class.
Get: Value(self: GuidAttribute) -> str
"""
|
'''Disciplina: Programação I
Trabalho prático ano lectivo 2013/2014
Realizado por Hiago Oliveira (29248) e Rui Oliveira (31511)
'''
class Village:
# Constructor method
# Used to create a new instance of Village, taking in arguments like
# its size and population, then builds the board used throughout the
# program
# inputs: size, population
# outputs: none
def __init__(self, size, population):
self.size = size
self.population = population
self.board = []
self.locations = dict()
for y in range(self.size):
self.board.append([])
for x in range(self.size):
self.board[y].append(0)
# populate() method
# Iterates over the number of population to fill the board with each
# villager's coordinates
# inputs: none
# outputs: none
def populate(self):
global bad_file
for i in range(self.population):
while True:
try:
if io_method == 1:
coords = input('{:d} Coords: '.format(i + 1)).split()
elif io_method == 2:
coords = f_input[i + 2].split()
for j in range(len(coords)):
coords[j] = int(coords[j])
# Storing in the dictionary the given coordinates. for eg:
# {1: [0, 0, 3, 2]}
self.locations[i + 1] = coords
# Checking if the given coordinates are already filled
if self.board[coords[1]][coords[0]] == 0:
if self.board[coords[3]][coords[2]] == 0:
self.board[coords[1]][coords[0]] = i + 1
self.board[coords[3]][coords[2]] = i + 1
break
else:
if io_method == 2:
print('Bad input file, please review it.')
bad_file = True
return
else:
raise ValueError
else:
if io_method == 2:
print('Bad input file, please review it.')
bad_file = True
return
else:
raise ValueError
except ValueError:
print('Coord already occupied... Try again.')
except IndexError:
print('Invalid coordinate format...')
# solve(b, p, l)
# The solve function has all the necessary arguments to start solving the
# puzzle, it will first create a pool of all possible paths from point to point
# then finding the correct combination of paths through other functions
# inputs: board, population, locations
# "locations" is a dictionary of villagers, each one with its corresponding
# coordinates for their potion and house
# outputs: none
def solve(board, population, locations):
solved_board = board.copy()
paths = {}
solve_key = []
vil_keys = []
# Retrieves from the dicionary the coordinates for the villager's potion
# then finds all possible paths from the potion to the house using the
# path_finder() function
for i in range(1, population + 1):
x = locations[i][0]
y = locations[i][1]
paths[i] = path_finder(solved_board, i, y, x)
# Creates a list with the villagers, for eg if this village has 3
# inhabitants, vil_keys will be [1, 2, 3]
for i in paths.keys():
vil_keys.append(i)
# sort_out() explanation further below
sort_out(paths, solved_board, vil_keys, 0, [], solve_key)
# io_method dictates whether the user chose to input values manually (1)
# or by providing a file (2). The only difference is if io_method == 1
# the solved puzzle will be printed directly in the screen instead of
# being written to a file
if io_method == 1:
if not solve_key:
print('\nAlesia')
else:
print('\nToutatis\n')
for i in range(len(vil_keys)):
for j in paths[vil_keys[i]][solve_key[i]]:
solved_board[j[0]][j[1]] = vil_keys[i]
draw_board(solved_board)
elif io_method == 2:
fout_name = fin_name[:3] + '.out'
temp = open(fout_name, 'w+')
if not solve_key:
temp.write('Alesia')
else:
temp.write('Toutatis\n')
for i in range(len(vil_keys)):
for j in paths[vil_keys[i]][solve_key[i]]:
solved_board[j[0]][j[1]] = vil_keys[i]
write_board(solved_board, temp)
temp.close()
print('%s has been created at your CWD.' % fout_name)
return
# path_finder()
# Used as an intermediary function to create the list of all possible paths,
# lather filled by path_crawler()
# inputs: board, i, y, x
# "i" is the current villager which possible paths are being generated.
# x and y are the coords of that villager's potion, or the starting point.
# outputs: pos_path
# "pos_path" is a list fileld with all possible paths from 'a' to 'b'.
def path_finder(board, i, y, x):
pos_path = []
path_crawler(board, i, y, x, pos_path, [], y, x)
return pos_path
# Directions used to travel the board
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# path_crawler()
# Generates all possible paths from 'a' to 'b', recursively
# inputs: board, i, y, x, path_list, stack, startY, startX
# outputs: none, but modifies path_list (possible paths)
def path_crawler(board, i, y, x, path_list, stack, startY, startX):
# Previously visited/tested paths are marked with a *
if board[y][x] == '*':
return
stack.append((y, x))
if board[y][x] == 0 or (y == startY and x == startX):
lastVal = board[y][x]
board[y][x] = '*'
for d in dirs:
if not valid(x + d[0], y + d[1], len(board)):
continue
path_crawler(board, i, y + d[1], x + d[0], path_list, stack,
startY, startX)
board[y][x] = lastVal
elif board[y][x] == i:
path_list.append(list(stack))
stack.pop()
# valid()
# Checks if the given coordinate is valid, i.e., if it's within the board
# inputs: x, y, size
# outputs: boolean
# True being a valide coordinate, False otherwise
def valid(x, y, size):
return x < size and y < size and x >= 0 and y >= 0
# sort_out()
# Receives a dictionary (paths) with all villagers and their possible solutions
# which then sorts out and finds the correct solution key, by excluding the
# paths that intersect with eachother and combining a set of paths that can be
# used to solve the puzzle
# inputs: paths, board, vil, index, stack, final_sol
# "vil" is a list of villagers, for eg if 3 villagers exist vil = [1, 2, 3]
# "final_sol" is a list of the correct key to solve the puzzle, for further
# explanation check the report.
# "stack" list used to store possible paths, pops the wrong ones.
def sort_out(paths, board, vil, index, stack, final_sol):
if len(vil) == 1 and index == 1:
return True
if index == len(vil):
return len(stack) == len(board) * len(board[index - 1])
for current in range(0, len(paths[vil[index]])):
path = paths[vil[index]][current]
if intersects(path, stack):
continue
final_sol.append(current)
if sort_out(paths, board, vil, index + 1, stack + path, final_sol):
return True
final_sol.pop()
return False
# intersects()
# Returns whether an item is present in both lists
# inputs: listA, listB
# outputs: boolean
def intersects(listA, listB):
for i in listA:
if i in listB:
return True
return False
# draw_board()
# Used to properly print "board", or a list of lists
# inputs: board
# outputs: none
def draw_board(board):
for item in board:
for j in item:
print(j, end=' ')
print()
# write_board()
# Same as draw_board(), but instead of printing directly to the screen,
# writes it in a file
# inputs: board, file
# outputs: none
def write_board(board, file):
for item in board:
for j in item:
file.write(str(j) + ' ')
file.write('\n')
if __name__ == '__main__':
# While True, the game runs. If the user later chooses not to play again,
# a 'break' statement will break out of it.
while True:
bad_file = False
print('Input values manually(1) or import them from a file(2)? ',
end='')
while True:
try:
io_method = int(input())
if io_method != 1 and io_method != 2:
raise ValueError
else:
break
except ValueError:
print('Not a valid choice...')
if io_method == 2:
f_input = []
while True:
try:
fin_name = input('Please enter the file name: ')
temp = open(fin_name, 'r')
# Fills a list f_input with the contents of a file
for line in temp:
f_input.append(line.rstrip())
temp.close()
break
except FileNotFoundError:
print('Error: No such file or directory.')
while True:
try:
if io_method == 1:
board_size = int(input('Village size: '))
elif io_method == 2:
board_size = int(f_input[0])
if board_size < 2 or board_size > 7:
if io_method == 2:
print('Bad input file, please review it.')
bad_file = True
break
else:
raise ValueError
else:
break
except ValueError:
print('Village size must be AN INTEGER between 2 and 7.')
# These "bad_file checks" are used to know if the file provided
# contains a bad variable or coordinate, eg a larger village than
# permitted, or a coordinate already occupied..
# These checks occur twice more down below.
if bad_file:
input('Press Enter to exit...')
break
while True:
try:
if io_method == 1:
vil_population = int(input('Village population: '))
elif io_method == 2:
vil_population = int(f_input[1])
if vil_population < 1 or vil_population > board_size:
if io_method == 2:
print('Bad input file, please review it.')
bad_file = True
break
else:
raise ValueError
else:
break
except ValueError:
print('Population must be between 1 and village size.')
if bad_file:
input('Press Enter to exit...')
break
# Creates a new instance of Village and then populates it
new_game = Village(board_size, vil_population)
new_game.populate()
if bad_file:
input('Press Enter to exit...')
break
#start solving
solve(new_game.board, vil_population, new_game.locations)
replay = input('\nReplay? Y/N ... ')
if replay == 'n' or replay == 'N':
break
elif replay == 'y' or replay == 'Y':
continue
else:
print('Interpreting vague answer as... no.')
input('Press Enter to exit...')
break
|
def palavras_repetidas(fileName, word):
file = open(fileName, 'r')
count = 0
for i in file.readlines():
if word in i:
count += 1
print(f'{word} aparece no arquivo {fileName} {count} vez(es).') |
n = int(input())
x = 0
for i in range(n):
l = set([j for j in input()])
if "+" in l:
x += 1
else :
x -= 1
print(x)
|
client = pymongo.MongoClient("mongodb+srv://usermgs:udUnpg6aJnCp9d2W@cluster0.2ivys.mongodb.net/baseteste?retryWrites=true&w=majority")
db = client.test
|
class Mammal:
x = 10
def walk(self):
print("Walking")
# class Dog:
# def walk(self):
# print("Walking")
# class Cat:
# def walk(self):
# print("Walking")
class Dog(Mammal):
def bark(self):
print("Woof, woof!")
class Cat(Mammal):
pass # Just used here as Python does not like empty classes. Pass just passes...
rover = Dog()
print(rover.x)
rover.bark()
fluffy = Cat()
fluffy.walk()
|
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=35):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá{id(self)}'
if __name__ == '__main__':
thaila = Pessoa(nome='Thaila')
junior = Pessoa(thaila, nome='Junior')
print(Pessoa.cumprimentar(junior))
print(id(junior))
print(junior.cumprimentar())
print(junior.nome)
print(junior.idade)
for filho in junior.filhos:
print(filho.nome)
junior.sobrenome = 'Reis'
del junior.filhos
junior.olhos = 1
print(junior.__dict__)
print(thaila.__dict__)
print(Pessoa.olhos)
print(thaila.olhos)
print(junior.olhos)
print(id(Pessoa.olhos), id(thaila.olhos), id(junior.olhos))
|
#
# @lc app=leetcode.cn id=1203 lang=python3
#
# [1203] print-in-order
#
None
# @lc code=end |
'''
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.
Example 1:
Input: [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Without loss of generality, we can assume the root node is at position (0, 0):
Then, the node with value 9 occurs at position (-1, -1);
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
The node with value 20 occurs at position (1, -1);
The node with value 7 occurs at position (2, -2).
Example 2:
Input: [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.
Note:
The tree will have between 1 and 1000 nodes.
Each node's value will be between 0 and 1000.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def verticalTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
# col: node.val
dic = {}
vec = [(root, 0)]
while vec:
next_vec = []
for node, col in vec:
if col not in dic:
dic[col] = [node.val]
else:
dic[col].append(node.val)
if node.left:
next_vec.append((node.left, col-1))
if node.right:
next_vec.append((node.right, col+1))
vec = sorted(next_vec, key = lambda x: (x[1], x[0].val))
res = []
for col in sorted(dic.keys()):
res.append(dic[col])
return res
|
def check_hgt(h):
if "cm" in h:
return 150 <= int(h.replace("cm","")) <= 193
elif "in" in h:
return 59 <= int(h.replace("in","")) <= 76
else:
return False
def check_hcl(h):
if h[0] != '#' or len(h) != 7:
return False
for x in h[1:]:
if not x in list("abcdef0123456789"):
return False
return True
def check_range(v, low, high):
return low <= int(v) <= high
validation = {
"hgt": check_hgt,
"hcl": check_hcl,
"pid": lambda x: len(x) == 9,
"byr": lambda x: check_range(x, 1920, 2002),
"iyr": lambda x: check_range(x, 2010, 2020),
"eyr": lambda x: check_range(x, 2020, 2030),
"ecl": lambda x: x in ["amb","blu","brn","gry", "grn", "hzl", "oth"],
"cid": lambda x: True
}
def validate_passport(p):
return len(p) == 8 or (len(p) == 7 and not p.get("cid", None))
#with open("test.txt", "rt") as file:
with open("day4.txt", "rt") as file:
valid = 0
valid2 = 0
passport = {}
passport2 = {}
for l in file.read().splitlines():
if l.strip() == "":
valid += validate_passport(passport)
valid2 += validate_passport(passport2)
passport = {}
passport2 = {}
else:
for x in l.strip().split(' '):
p = x.split(":")
passport[p[0]] = p[1]
if (validation[p[0]](p[1])):
passport2[p[0]] = p[1]
valid += validate_passport(passport)
valid2 += validate_passport(passport2)
print (valid)
print (valid2)
|
def test_deploying_contract(client, hex_accounts):
pre_balance = client.get_balance(hex_accounts[1])
client.send_transaction(
_from=hex_accounts[0],
to=hex_accounts[1],
value=1234,
)
post_balance = client.get_balance(hex_accounts[1])
assert post_balance - pre_balance == 1234
|
if __name__ == '__main__':
_, X = input().split()
subjects = list()
for _ in range(int(X)):
subjects.append(map(float, input().split()))
for i in zip(*subjects):
print("{0:.1f}".format(sum(i)/len(i)))
|
promt = "Here you can enter"
promt += "a series of toppings>>>"
message = True
while message:
message = input(promt)
if message == "Quit":
print(" I'll add " + message + " to your pizza.")
else:
break
promt = "How old are you?"
promt += "\nEnter 'quit' when you are finished >>>"
while True:
age = input(promt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket cost is free")
elif age < 13:
print("Your ticket price is 10 $ ")
else:
print("Your ticket price is 15 $")
sandwich_orders = ["hamburger","cheeseburger","veggie burger", "royal"]
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print("we are working on "+ sandwich + " at the moment")
finished_sandwiches.append(sandwich)
print("\n")
for sandwich in finished_sandwiches:
print("We have made " + sandwich + ", you can take it now")
sandwich_orders = ["pastrami","hamburger","cheeseburger","pastrami","veggie burger", "royal","pastrami"]
finished_sandwiches = []
print("We are sorry, pastrami sandwich ran out of")
while "pastrami" in sandwich_orders:
sandwich_orders.remove("pastrami")
print("\n")
while sandwich_orders:
sandwich = sandwich_orders.pop()
print("Your order "+ sandwich + " will be prepared soon ! ")
finished_sandwiches.append(sandwich)
print("\n")
for sandwich in finished_sandwiches:
print("Your order " + sandwich + " is ready, take it")
#
name_promt = "Whats your name?>>>"
place_promt = "Where would you like to go?>>>"
next_promt = "\nWould you like to go with someone?(yes/no)>>>"
responses = {}
while True:
name = input(name_promt)
place = input(place_promt)
responses[name] = place
other_question = input(next_promt)
if other_question == "yes":
break
print(">>>results<<<")
for name,place in responses.items():
print(name.title() + " would like to go in " + place.title() + ".") |
def foo(a, b):
x = a * b
y = 3
return y
def foo(a, b):
x = __report_assign(7, 8, 3)
x = __report_assign(pos, v, 3)
y = __report_assign(lineno, col, 3)
print("hello world")
foo(3, 2)
report_call(0, 3, foo, (report_eval(3), report_eval(2),))
|
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
if __name__ == '__main__':
a = "11"
b = "1"
solution = Solution()
result = solution.addBinary(a, b)
print(result)
result1 = int(a, 2)
result2 = int(b, 2)
print(result1)
print(result2)
print(bin(result1 + result2))
print(bin(result1 + result2)[2:])
|
"""
[intermediate] challenge #5
Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/pnhtj/2132012_challenge_5_intermediate/
"""
words = []
sorted_words = []
with open('intermediate/5/words.txt', 'r') as fp:
words = fp.read().split()
sorted_words = [''.join(sorted(word)) for word in words]
fp.close()
word_dict = {}
for ind, word in enumerate(sorted_words):
if word in word_dict:
word_dict[word].append(words[ind])
else:
word_dict[word] = [words[ind]]
print('\n'.join([', '.join(word_set) for word_set in word_dict.values() if len(word_set) > 1]))
|
a=int(input())
b=int(input())
print (a/b)
a=float(a)
b=float(b)
print (a/b) |
"""Abstract planet type."""
class Planet(type):
"""Abstract Planet object."""
MEAN_RADIUS = (None, None) # [km] ± err [km]
RADII = ((None, None), (None, None), (None, None)) # [km] ± err [km]
def __str__(cls):
return cls.__name__
def __repr__(cls):
return f'<{cls.__class__.__name__}> {cls}'
def __eq__(cls, other):
return str(cls).lower() == other.lower()
@property
def radius(cls):
"""Mean radius [km]."""
return cls.MEAN_RADIUS[0]
@property
def r(cls):
"""Mean radius (shortcut) [km]."""
return cls.radius
@property
def radii(cls):
"""Planet RADII (a, b, c) [km]."""
return tuple([abc[0] for abc in cls.RADII])
@property
def a(cls):
"""Planet a-axis radius [km]."""
return cls.RADII[0][0]
@property
def b(cls):
"""Planet b-axis radius [km]."""
return cls.RADII[1][0]
@property
def c(cls):
"""Planet c-axis radius [km]."""
return cls.RADII[2][0]
def lower(cls):
"""Planet name in lowercase."""
return str(cls).lower()
|
# -*- coding: utf-8 -*-
"""
Individual scratchpad and maybe up-to-date CDP instance scrapers.
"""
|
def test_Dict():
x: dict[i32, i32]
x = {1: 2, 3: 4}
# x = {1: "2", "3": 4} -> sematic error
y: dict[str, i32]
y = {"a": -1, "b": -2}
z: i32
z = y["a"]
z = y["b"]
z = x[1]
def test_dict_insert():
y: dict[str, i32]
y = {"a": -1, "b": -2}
y["c"] = -3
def test_dict_get():
y: dict[str, i32]
y = {"a": -1, "b": -2}
x: i32
x = y.get("a")
x = y.get("a", 0)
|
states = {'Pending', 'Ready', 'Creating', 'Running', 'Cancelled', 'Error', 'Failed', 'Success'}
complete_states = ('Cancelled', 'Error', 'Failed', 'Success')
valid_state_transitions = {
'Pending': {'Ready'},
'Ready': {'Creating', 'Running', 'Cancelled', 'Error'},
'Creating': {'Ready', 'Running'},
'Running': {'Ready', 'Cancelled', 'Error', 'Failed', 'Success'},
'Cancelled': set(),
'Error': set(),
'Failed': set(),
'Success': set(),
}
tasks = ('input', 'main', 'output')
memory_types = ('lowmem', 'standard', 'highmem')
HTTP_CLIENT_MAX_SIZE = 8 * 1024 * 1024
BATCH_FORMAT_VERSION = 6
STATUS_FORMAT_VERSION = 5
INSTANCE_VERSION = 22
MAX_PERSISTENT_SSD_SIZE_GIB = 64 * 1024
RESERVED_STORAGE_GB_PER_CORE = 5
|
def assigned_type_mismatch():
x = 666
x = '666'
return x
def annotation_type_mismatch(x: int = '666'):
return x
def assigned_type_mismatch_between_calls(case):
if case:
x = 666
else:
x = '666'
return x
|
# https://www.codewars.com/kata/576757b1df89ecf5bd00073b/train/python
def tower_builder(n_floors):
times = 1
space = ((2*n_floors -1) // 2)
tower = []
for _ in range(n_floors):
tower.append((' '*space) + ('*' * times) + (' '*space))
times += 2
space -= 1
return tower
|
#! /usr/bin/env python
# Programs that are runnable.
ns3_runnable_programs = ['build/src/aodv/examples/ns3.27-aodv-debug', 'build/src/bridge/examples/ns3.27-csma-bridge-debug', 'build/src/bridge/examples/ns3.27-csma-bridge-one-hop-debug', 'build/src/buildings/examples/ns3.27-buildings-pathloss-profiler-debug', 'build/src/config-store/examples/ns3.27-config-store-save-debug', 'build/src/core/examples/ns3.27-main-callback-debug', 'build/src/core/examples/ns3.27-sample-simulator-debug', 'build/src/core/examples/ns3.27-main-ptr-debug', 'build/src/core/examples/ns3.27-main-random-variable-debug', 'build/src/core/examples/ns3.27-main-random-variable-stream-debug', 'build/src/core/examples/ns3.27-sample-random-variable-debug', 'build/src/core/examples/ns3.27-sample-random-variable-stream-debug', 'build/src/core/examples/ns3.27-command-line-example-debug', 'build/src/core/examples/ns3.27-hash-example-debug', 'build/src/core/examples/ns3.27-sample-log-time-format-debug', 'build/src/core/examples/ns3.27-test-string-value-formatting-debug', 'build/src/csma/examples/ns3.27-csma-one-subnet-debug', 'build/src/csma/examples/ns3.27-csma-broadcast-debug', 'build/src/csma/examples/ns3.27-csma-packet-socket-debug', 'build/src/csma/examples/ns3.27-csma-multicast-debug', 'build/src/csma/examples/ns3.27-csma-raw-ip-socket-debug', 'build/src/csma/examples/ns3.27-csma-ping-debug', 'build/src/csma-layout/examples/ns3.27-csma-star-debug', 'build/src/dsdv/examples/ns3.27-dsdv-manet-debug', 'build/src/dsr/examples/ns3.27-dsr-debug', 'build/src/energy/examples/ns3.27-li-ion-energy-source-debug', 'build/src/energy/examples/ns3.27-rv-battery-model-test-debug', 'build/src/energy/examples/ns3.27-basic-energy-model-test-debug', 'build/src/fd-net-device/examples/ns3.27-dummy-network-debug', 'build/src/fd-net-device/examples/ns3.27-fd2fd-onoff-debug', 'build/src/internet/examples/ns3.27-main-simple-debug', 'build/src/internet-apps/examples/ns3.27-dhcp-example-debug', 'build/src/lr-wpan/examples/ns3.27-lr-wpan-packet-print-debug', 'build/src/lr-wpan/examples/ns3.27-lr-wpan-phy-test-debug', 'build/src/lr-wpan/examples/ns3.27-lr-wpan-data-debug', 'build/src/lr-wpan/examples/ns3.27-lr-wpan-error-model-plot-debug', 'build/src/lr-wpan/examples/ns3.27-lr-wpan-error-distance-plot-debug', 'build/src/lte/examples/ns3.27-lena-cqi-threshold-debug', 'build/src/lte/examples/ns3.27-lena-dual-stripe-debug', 'build/src/lte/examples/ns3.27-lena-fading-debug', 'build/src/lte/examples/ns3.27-lena-intercell-interference-debug', 'build/src/lte/examples/ns3.27-lena-pathloss-traces-debug', 'build/src/lte/examples/ns3.27-lena-profiling-debug', 'build/src/lte/examples/ns3.27-lena-rem-debug', 'build/src/lte/examples/ns3.27-lena-rem-sector-antenna-debug', 'build/src/lte/examples/ns3.27-lena-rlc-traces-debug', 'build/src/lte/examples/ns3.27-lena-simple-debug', 'build/src/lte/examples/ns3.27-lena-simple-epc-debug', 'build/src/lte/examples/ns3.27-lena-deactivate-bearer-debug', 'build/src/lte/examples/ns3.27-lena-x2-handover-debug', 'build/src/lte/examples/ns3.27-lena-x2-handover-measures-debug', 'build/src/lte/examples/ns3.27-lena-frequency-reuse-debug', 'build/src/lte/examples/ns3.27-lena-distributed-ffr-debug', 'build/src/lte/examples/ns3.27-lena-uplink-power-control-debug', 'build/src/mesh/examples/ns3.27-mesh-debug', 'build/src/mobility/examples/ns3.27-main-grid-topology-debug', 'build/src/mobility/examples/ns3.27-main-random-topology-debug', 'build/src/mobility/examples/ns3.27-main-random-walk-debug', 'build/src/mobility/examples/ns3.27-mobility-trace-example-debug', 'build/src/mobility/examples/ns3.27-ns2-mobility-trace-debug', 'build/src/mobility/examples/ns3.27-bonnmotion-ns2-example-debug', 'build/src/mpi/examples/ns3.27-simple-distributed-debug', 'build/src/mpi/examples/ns3.27-third-distributed-debug', 'build/src/mpi/examples/ns3.27-nms-p2p-nix-distributed-debug', 'build/src/mpi/examples/ns3.27-simple-distributed-empty-node-debug', 'build/src/netanim/examples/ns3.27-dumbbell-animation-debug', 'build/src/netanim/examples/ns3.27-grid-animation-debug', 'build/src/netanim/examples/ns3.27-star-animation-debug', 'build/src/netanim/examples/ns3.27-wireless-animation-debug', 'build/src/netanim/examples/ns3.27-uan-animation-debug', 'build/src/netanim/examples/ns3.27-colors-link-description-debug', 'build/src/netanim/examples/ns3.27-resources-counters-debug', 'build/src/network/examples/ns3.27-main-packet-header-debug', 'build/src/network/examples/ns3.27-main-packet-tag-debug', 'build/src/network/examples/ns3.27-packet-socket-apps-debug', 'build/src/nix-vector-routing/examples/ns3.27-nix-simple-debug', 'build/src/nix-vector-routing/examples/ns3.27-nms-p2p-nix-debug', 'build/src/olsr/examples/ns3.27-simple-point-to-point-olsr-debug', 'build/src/olsr/examples/ns3.27-olsr-hna-debug', 'build/src/point-to-point/examples/ns3.27-main-attribute-value-debug', 'build/src/propagation/examples/ns3.27-main-propagation-loss-debug', 'build/src/propagation/examples/ns3.27-jakes-propagation-model-example-debug', 'build/src/sixlowpan/examples/ns3.27-example-sixlowpan-debug', 'build/src/sixlowpan/examples/ns3.27-example-ping-lr-wpan-debug', 'build/src/spectrum/examples/ns3.27-adhoc-aloha-ideal-phy-debug', 'build/src/spectrum/examples/ns3.27-adhoc-aloha-ideal-phy-matrix-propagation-loss-model-debug', 'build/src/spectrum/examples/ns3.27-adhoc-aloha-ideal-phy-with-microwave-oven-debug', 'build/src/spectrum/examples/ns3.27-tv-trans-example-debug', 'build/src/spectrum/examples/ns3.27-tv-trans-regional-example-debug', 'build/src/stats/examples/ns3.27-gnuplot-example-debug', 'build/src/stats/examples/ns3.27-double-probe-example-debug', 'build/src/stats/examples/ns3.27-time-probe-example-debug', 'build/src/stats/examples/ns3.27-gnuplot-aggregator-example-debug', 'build/src/stats/examples/ns3.27-gnuplot-helper-example-debug', 'build/src/stats/examples/ns3.27-file-aggregator-example-debug', 'build/src/stats/examples/ns3.27-file-helper-example-debug', 'build/src/topology-read/examples/ns3.27-topology-example-sim-debug', 'build/src/traffic-control/examples/ns3.27-red-tests-debug', 'build/src/traffic-control/examples/ns3.27-red-vs-ared-debug', 'build/src/traffic-control/examples/ns3.27-adaptive-red-tests-debug', 'build/src/traffic-control/examples/ns3.27-pfifo-vs-red-debug', 'build/src/traffic-control/examples/ns3.27-codel-vs-pfifo-basic-test-debug', 'build/src/traffic-control/examples/ns3.27-codel-vs-pfifo-asymmetric-debug', 'build/src/traffic-control/examples/ns3.27-pie-example-debug', 'build/src/uan/examples/ns3.27-uan-cw-example-debug', 'build/src/uan/examples/ns3.27-uan-rc-example-debug', 'build/src/virtual-net-device/examples/ns3.27-virtual-net-device-debug', 'build/src/wave/examples/ns3.27-wave-simple-80211p-debug', 'build/src/wave/examples/ns3.27-wave-simple-device-debug', 'build/src/wave/examples/ns3.27-vanet-routing-compare-debug', 'build/src/wifi/examples/ns3.27-wifi-phy-test-debug', 'build/src/wifi/examples/ns3.27-test-interference-helper-debug', 'build/src/wifi/examples/ns3.27-wifi-manager-example-debug', 'build/src/wimax/examples/ns3.27-wimax-ipv4-debug', 'build/src/wimax/examples/ns3.27-wimax-multicast-debug', 'build/src/wimax/examples/ns3.27-wimax-simple-debug', 'build/examples/energy/ns3.27-energy-model-example-debug', 'build/examples/energy/ns3.27-energy-model-with-harvesting-example-debug', 'build/examples/error-model/ns3.27-simple-error-model-debug', 'build/examples/ipv6/ns3.27-icmpv6-redirect-debug', 'build/examples/ipv6/ns3.27-ping6-debug', 'build/examples/ipv6/ns3.27-radvd-debug', 'build/examples/ipv6/ns3.27-radvd-two-prefix-debug', 'build/examples/ipv6/ns3.27-test-ipv6-debug', 'build/examples/ipv6/ns3.27-fragmentation-ipv6-debug', 'build/examples/ipv6/ns3.27-fragmentation-ipv6-two-MTU-debug', 'build/examples/ipv6/ns3.27-loose-routing-ipv6-debug', 'build/examples/ipv6/ns3.27-wsn-ping6-debug', 'build/examples/matrix-topology/ns3.27-matrix-topology-debug', 'build/examples/naming/ns3.27-object-names-debug', 'build/examples/routing/ns3.27-dynamic-global-routing-debug', 'build/examples/routing/ns3.27-static-routing-slash32-debug', 'build/examples/routing/ns3.27-global-routing-slash32-debug', 'build/examples/routing/ns3.27-global-injection-slash32-debug', 'build/examples/routing/ns3.27-simple-global-routing-debug', 'build/examples/routing/ns3.27-simple-alternate-routing-debug', 'build/examples/routing/ns3.27-mixed-global-routing-debug', 'build/examples/routing/ns3.27-simple-routing-ping6-debug', 'build/examples/routing/ns3.27-manet-routing-compare-debug', 'build/examples/routing/ns3.27-ripng-simple-network-debug', 'build/examples/routing/ns3.27-rip-simple-network-debug', 'build/examples/routing/ns3.27-global-routing-multi-switch-plus-router-debug', 'build/examples/socket/ns3.27-socket-bound-static-routing-debug', 'build/examples/socket/ns3.27-socket-bound-tcp-static-routing-debug', 'build/examples/socket/ns3.27-socket-options-ipv4-debug', 'build/examples/socket/ns3.27-socket-options-ipv6-debug', 'build/examples/stats/ns3.27-wifi-example-sim-debug', 'build/examples/tcp/ns3.27-tcp-large-transfer-debug', 'build/examples/tcp/ns3.27-tcp-nsc-lfn-debug', 'build/examples/tcp/ns3.27-tcp-nsc-zoo-debug', 'build/examples/tcp/ns3.27-tcp-star-server-debug', 'build/examples/tcp/ns3.27-star-debug', 'build/examples/tcp/ns3.27-tcp-bulk-send-debug', 'build/examples/tcp/ns3.27-tcp-pcap-nanosec-example-debug', 'build/examples/tcp/ns3.27-tcp-nsc-comparison-debug', 'build/examples/tcp/ns3.27-tcp-variants-comparison-debug', 'build/examples/traffic-control/ns3.27-traffic-control-debug', 'build/examples/traffic-control/ns3.27-queue-discs-benchmark-debug', 'build/examples/traffic-control/ns3.27-red-vs-fengadaptive-debug', 'build/examples/traffic-control/ns3.27-red-vs-nlred-debug', 'build/examples/tutorial/ns3.27-hello-simulator-debug', 'build/examples/tutorial/ns3.27-first-debug', 'build/examples/tutorial/ns3.27-second-debug', 'build/examples/tutorial/ns3.27-third-debug', 'build/examples/tutorial/ns3.27-fourth-debug', 'build/examples/tutorial/ns3.27-fifth-debug', 'build/examples/tutorial/ns3.27-sixth-debug', 'build/examples/tutorial/ns3.27-seventh-debug', 'build/examples/udp/ns3.27-udp-echo-debug', 'build/examples/udp-client-server/ns3.27-udp-client-server-debug', 'build/examples/udp-client-server/ns3.27-udp-trace-client-server-debug', 'build/examples/wireless/ns3.27-mixed-wired-wireless-debug', 'build/examples/wireless/ns3.27-wifi-adhoc-debug', 'build/examples/wireless/ns3.27-wifi-clear-channel-cmu-debug', 'build/examples/wireless/ns3.27-wifi-ap-debug', 'build/examples/wireless/ns3.27-wifi-wired-bridging-debug', 'build/examples/wireless/ns3.27-multirate-debug', 'build/examples/wireless/ns3.27-wifi-simple-adhoc-debug', 'build/examples/wireless/ns3.27-wifi-simple-adhoc-grid-debug', 'build/examples/wireless/ns3.27-wifi-simple-infra-debug', 'build/examples/wireless/ns3.27-wifi-simple-interference-debug', 'build/examples/wireless/ns3.27-wifi-blockack-debug', 'build/examples/wireless/ns3.27-ofdm-validation-debug', 'build/examples/wireless/ns3.27-ofdm-ht-validation-debug', 'build/examples/wireless/ns3.27-ofdm-vht-validation-debug', 'build/examples/wireless/ns3.27-wifi-hidden-terminal-debug', 'build/examples/wireless/ns3.27-ht-wifi-network-debug', 'build/examples/wireless/ns3.27-vht-wifi-network-debug', 'build/examples/wireless/ns3.27-wifi-timing-attributes-debug', 'build/examples/wireless/ns3.27-wifi-sleep-debug', 'build/examples/wireless/ns3.27-power-adaptation-distance-debug', 'build/examples/wireless/ns3.27-power-adaptation-interference-debug', 'build/examples/wireless/ns3.27-rate-adaptation-distance-debug', 'build/examples/wireless/ns3.27-wifi-aggregation-debug', 'build/examples/wireless/ns3.27-simple-ht-hidden-stations-debug', 'build/examples/wireless/ns3.27-80211n-mimo-debug', 'build/examples/wireless/ns3.27-mixed-network-debug', 'build/examples/wireless/ns3.27-wifi-tcp-debug', 'build/examples/wireless/ns3.27-80211e-txop-debug', 'build/examples/wireless/ns3.27-wifi-spectrum-per-example-debug', 'build/examples/wireless/ns3.27-wifi-spectrum-per-interference-debug', 'build/examples/wireless/ns3.27-wifi-spectrum-saturation-example-debug', 'build/examples/wireless/ns3.27-ofdm-he-validation-debug', 'build/examples/wireless/ns3.27-he-wifi-network-debug', 'build/examples/wireless/ns3.27-wifi-multi-tos-debug', 'build/examples/wireless/ns3.27-wifi-backward-compatibility-debug', 'build/scratch/ns3.27-scratch-simulator-debug', 'build/scratch/subdir/ns3.27-subdir-debug']
# Scripts that are runnable.
ns3_runnable_scripts = ['csma-bridge.py', 'sample-simulator.py', 'wifi-olsr-flowmon.py', 'simple-routing-ping6.py', 'first.py', 'second.py', 'third.py', 'mixed-wired-wireless.py', 'wifi-ap.py']
|
# Arithmetic progression
# A + (A+B) + (A+2B) + (A+3B) + ... + (A+(C-1)B))
def main():
N = int(input("data:\n"))
l = []
for x in range(0,N):
a,b,c = input().split(" ")
a,b,c = int(a),int(b),int(c)
s = 0
for each in range(0,c):
s += a + (b*each)
l.append(s)
print("\nanswer:")
for each in l:
print(each, end=" ")
main()
|
#!/usr/bin/env python3
# Algorithm: Quick sort
# Referrence: https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py
def quick_sort(num_list):
"""
Quick sort in Python
If length of the list is 1 or less, there is no point in sorting it.
Hence, the code works on lists with sizes greater than 1
"""
if len(num_list) <= 1:
return(num_list)
else:
pivot = num_list.pop()
less_than = []
greater_than = []
for num in num_list:
if num < pivot:
less_than.append(num)
elif num > pivot:
greater_than.append(num)
#print(less_than)
#print(pivot)
#print(greater_than)
return quick_sort(less_than) + [pivot] + quick_sort(greater_than)
num_list = [10, -1, 100, 23, 5, 98, 45, 76, -545, -300, 9999]
print(quick_sort(num_list))
|
col = {
"owid": {
"Notes": "notes",
"Entity": "entity",
"Date": "time",
"Source URL": "src",
"Source label": "src_lb",
"Cumulative total": "tot_n_tests",
"Daily change in cumulative total": "n_tests",
"Cumulative total per thousand": "tot_n_tests_pthab",
"Daily change in cumulative total per thousand": "n_tests_pthab",
"General source label": "source",
"General source URL": "source_url",
"Short description": "source_desc",
"Detailed description": "source_desc_detailed",
}
}
var = {
"owid": {}
}
|
# https://codeforces.com/problemset/problem/1030/A
n = int(input())
o = list(map(int, input().split()))
print('HARD' if o.count(1) != 0 else 'EASY') |
class Solution:
# @param {integer[]} candidates
# @param {integer} target
# @return {integer[][]}
def combinationSum(self, candidates, target):
candidates.sort()
return self.combsum(candidates, target)
def combsum(self, nums, target):
if target == 0:
return [[]]
if not nums or nums[0] > target or target < 1:
return []
res = []
for i in range(len(nums)):
num = nums[i]
pre = [num]
t = target
while t >= num:
t -= num
subs = self.combsum(nums[i + 1:], t)
for sub in subs:
res.append(pre + sub)
pre += [num]
return res
|
def decimal2base(num, base):
convert_string = "0123456789ABCDEF"
if num < base:
return convert_string[num]
remainder = num % base
num = num // base
return decimal2base(num, base) + convert_string[remainder]
print(decimal2base(1453, 16))
|
# wykys 2019
def bin_print(byte_array: list, num_in_line: int = 8, space: str = ' | '):
def bin_to_str(byte_array: list) -> str:
return ''.join([
chr(c) if c > 32 and c < 127 else '.' for c in byte_array
])
tmp = ''
for i, byte in enumerate(byte_array):
tmp = ''.join([tmp, f'{byte:02X}'])
if (i+1) % num_in_line:
tmp = ''.join([tmp, ' '])
else:
tmp = ''.join([
tmp,
space,
bin_to_str(byte_array[i-num_in_line+1:i+1]),
'\n'
])
if (i+1) % num_in_line:
tmp = ''.join([
tmp,
' '*(3*(num_in_line - ((i+1) % num_in_line)) - 1),
space,
bin_to_str(byte_array[i - ((i+1) % num_in_line) + 1:]),
'\n'
])
print(tmp)
|
expected_output = {
'environment-information': {
'environment-item': [{
'class': 'Temp',
'name': 'PSM 0',
'status': 'OK',
'temperature': {
'#text': '25 '
'degrees '
'C '
'/ '
'77 '
'degrees '
'F',
'@junos:celsius': '25'
}
}, {
'class': 'Temp',
'name': 'PSM 1',
'status': 'OK',
'temperature': {
'#text': '24 '
'degrees '
'C '
'/ '
'75 '
'degrees '
'F',
'@junos:celsius': '24'
}
}, {
'class': 'Temp',
'name': 'PSM 2',
'status': 'OK',
'temperature': {
'#text': '24 '
'degrees '
'C '
'/ '
'75 '
'degrees '
'F',
'@junos:celsius': '24'
}
}, {
'class': 'Temp',
'name': 'PSM 3',
'status': 'OK',
'temperature': {
'#text': '23 '
'degrees '
'C '
'/ '
'73 '
'degrees '
'F',
'@junos:celsius': '23'
}
}, {
'class': 'Temp',
'name': 'PSM 4',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 5',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 6',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 7',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 8',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 9',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'PSM 10',
'status': 'OK',
'temperature': {
'#text': '30 '
'degrees '
'C '
'/ '
'86 '
'degrees '
'F',
'@junos:celsius': '30'
}
}, {
'class': 'Temp',
'name': 'PSM 11',
'status': 'OK',
'temperature': {
'#text': '30 '
'degrees '
'C '
'/ '
'86 '
'degrees '
'F',
'@junos:celsius': '30'
}
}, {
'class': 'Temp',
'name': 'PSM 12',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 13',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 14',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 15',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 16',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PSM 17',
'status': 'Check'
}, {
'class': 'Temp',
'name': 'PDM 0',
'status': 'OK'
}, {
'class': 'Temp',
'name': 'PDM 1',
'status': 'OK'
}, {
'class': 'Temp',
'name': 'PDM 2',
'status': 'OK'
}, {
'class': 'Temp',
'name': 'PDM 3',
'status': 'OK'
}, {
'class': 'Temp',
'name': 'CB 0 IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '39 '
'degrees '
'C '
'/ '
'102 '
'degrees '
'F',
'@junos:celsius': '39'
}
}, {
'class': 'Temp',
'name': 'CB 0 IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '36 '
'degrees '
'C '
'/ '
'96 '
'degrees '
'F',
'@junos:celsius': '36'
}
}, {
'class': 'Temp',
'name': 'CB 0 IntakeC-Zone0',
'status': 'OK',
'temperature': {
'#text': '51 '
'degrees '
'C '
'/ '
'123 '
'degrees '
'F',
'@junos:celsius': '51'
}
}, {
'class': 'Temp',
'name': 'CB 0 '
'ExhaustA-Zone0',
'status': 'OK',
'temperature': {
'#text': '40 '
'degrees '
'C '
'/ '
'104 '
'degrees '
'F',
'@junos:celsius': '40'
}
}, {
'class': 'Temp',
'name': 'CB 0 '
'ExhaustB-Zone1',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'CB 0 TCBC-Zone0',
'status': 'OK',
'temperature': {
'#text': '45 '
'degrees '
'C '
'/ '
'113 '
'degrees '
'F',
'@junos:celsius': '45'
}
}, {
'class': 'Temp',
'name': 'CB 1 IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'CB 1 IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'CB 1 IntakeC-Zone0',
'status': 'OK',
'temperature': {
'#text': '33 '
'degrees '
'C '
'/ '
'91 '
'degrees '
'F',
'@junos:celsius': '33'
}
}, {
'class': 'Temp',
'name': 'CB 1 '
'ExhaustA-Zone0',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'CB 1 '
'ExhaustB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'CB 1 TCBC-Zone0',
'status': 'OK',
'temperature': {
'#text': '39 '
'degrees '
'C '
'/ '
'102 '
'degrees '
'F',
'@junos:celsius': '39'
}
}, {
'class': 'Temp',
'name': 'SPMB 0 Intake',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SPMB 1 Intake',
'status': 'OK',
'temperature': {
'#text': '33 '
'degrees '
'C '
'/ '
'91 '
'degrees '
'F',
'@junos:celsius': '33'
}
}, {
'class': 'Temp',
'name': 'Routing Engine 0',
'status': 'OK',
'temperature': {
'#text': '43 '
'degrees '
'C '
'/ '
'109 '
'degrees '
'F',
'@junos:celsius': '43'
}
}, {
'class': 'Temp',
'name': 'Routing Engine 0 '
'CPU',
'status': 'OK',
'temperature': {
'#text': '39 '
'degrees '
'C '
'/ '
'102 '
'degrees '
'F',
'@junos:celsius': '39'
}
}, {
'class': 'Temp',
'name': 'Routing Engine 1',
'status': 'OK',
'temperature': {
'#text': '40 '
'degrees '
'C '
'/ '
'104 '
'degrees '
'F',
'@junos:celsius': '40'
}
}, {
'class': 'Temp',
'name': 'Routing Engine 1 '
'CPU',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SFB 0 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '37 '
'degrees '
'C '
'/ '
'98 '
'degrees '
'F',
'@junos:celsius': '37'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '45 '
'degrees '
'C '
'/ '
'113 '
'degrees '
'F',
'@junos:celsius': '45'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '36 '
'degrees '
'C '
'/ '
'96 '
'degrees '
'F',
'@junos:celsius': '36'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '63 '
'degrees '
'C '
'/ '
'145 '
'degrees '
'F',
'@junos:celsius': '63'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '55 '
'degrees '
'C '
'/ '
'131 '
'degrees '
'F',
'@junos:celsius': '55'
}
}, {
'class': 'Temp',
'name': 'SFB 0 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'SFB 1 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '42 '
'degrees '
'C '
'/ '
'107 '
'degrees '
'F',
'@junos:celsius': '42'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '63 '
'degrees '
'C '
'/ '
'145 '
'degrees '
'F',
'@junos:celsius': '63'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'SFB 1 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'SFB 2 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '42 '
'degrees '
'C '
'/ '
'107 '
'degrees '
'F',
'@junos:celsius': '42'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '30 '
'degrees '
'C '
'/ '
'86 '
'degrees '
'F',
'@junos:celsius': '30'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '60 '
'degrees '
'C '
'/ '
'140 '
'degrees '
'F',
'@junos:celsius': '60'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'SFB 2 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '56 '
'degrees '
'C '
'/ '
'132 '
'degrees '
'F',
'@junos:celsius': '56'
}
}, {
'class': 'Temp',
'name': 'SFB 3 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '42 '
'degrees '
'C '
'/ '
'107 '
'degrees '
'F',
'@junos:celsius': '42'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '61 '
'degrees '
'C '
'/ '
'141 '
'degrees '
'F',
'@junos:celsius': '61'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'SFB 3 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'SFB 4 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '42 '
'degrees '
'C '
'/ '
'107 '
'degrees '
'F',
'@junos:celsius': '42'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '64 '
'degrees '
'C '
'/ '
'147 '
'degrees '
'F',
'@junos:celsius': '64'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'SFB 4 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'SFB 5 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '41 '
'degrees '
'C '
'/ '
'105 '
'degrees '
'F',
'@junos:celsius': '41'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '31 '
'degrees '
'C '
'/ '
'87 '
'degrees '
'F',
'@junos:celsius': '31'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '63 '
'degrees '
'C '
'/ '
'145 '
'degrees '
'F',
'@junos:celsius': '63'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'SFB 5 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'SFB 6 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '42 '
'degrees '
'C '
'/ '
'107 '
'degrees '
'F',
'@junos:celsius': '42'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '34 '
'degrees '
'C '
'/ '
'93 '
'degrees '
'F',
'@junos:celsius': '34'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '62 '
'degrees '
'C '
'/ '
'143 '
'degrees '
'F',
'@junos:celsius': '62'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'SFB 6 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '49 '
'degrees '
'C '
'/ '
'120 '
'degrees '
'F',
'@junos:celsius': '49'
}
}, {
'class': 'Temp',
'name': 'SFB 7 Intake-Zone0',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'Exhaust-Zone1',
'status': 'OK',
'temperature': {
'#text': '43 '
'degrees '
'C '
'/ '
'109 '
'degrees '
'F',
'@junos:celsius': '43'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'IntakeA-Zone0',
'status': 'OK',
'temperature': {
'#text': '31 '
'degrees '
'C '
'/ '
'87 '
'degrees '
'F',
'@junos:celsius': '31'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'IntakeB-Zone1',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'Exhaust-Zone0',
'status': 'OK',
'temperature': {
'#text': '35 '
'degrees '
'C '
'/ '
'95 '
'degrees '
'F',
'@junos:celsius': '35'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'SFB-XF2-Zone1',
'status': 'OK',
'temperature': {
'#text': '65 '
'degrees '
'C '
'/ '
'149 '
'degrees '
'F',
'@junos:celsius': '65'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'SFB-XF1-Zone0',
'status': 'OK',
'temperature': {
'#text': '56 '
'degrees '
'C '
'/ '
'132 '
'degrees '
'F',
'@junos:celsius': '56'
}
}, {
'class': 'Temp',
'name': 'SFB 7 '
'SFB-XF0-Zone0',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'FPC 0 Intake',
'status': 'OK',
'temperature': {
'#text': '29 '
'degrees '
'C '
'/ '
'84 '
'degrees '
'F',
'@junos:celsius': '29'
}
}, {
'class': 'Temp',
'name': 'FPC 0 Exhaust A',
'status': 'OK',
'temperature': {
'#text': '53 '
'degrees '
'C '
'/ '
'127 '
'degrees '
'F',
'@junos:celsius': '53'
}
}, {
'class': 'Temp',
'name': 'FPC 0 Exhaust B',
'status': 'OK',
'temperature': {
'#text': '54 '
'degrees '
'C '
'/ '
'129 '
'degrees '
'F',
'@junos:celsius': '54'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 0 TSen',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 0 Chip',
'status': 'OK',
'temperature': {
'#text': '63 '
'degrees '
'C '
'/ '
'145 '
'degrees '
'F',
'@junos:celsius': '63'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 0 XR2 0 '
'TSen',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 0 XR2 0 '
'Chip',
'status': 'OK',
'temperature': {
'#text': '80 '
'degrees '
'C '
'/ '
'176 '
'degrees '
'F',
'@junos:celsius': '80'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 0 XR2 1 '
'TSen',
'status': 'OK',
'temperature': {
'#text': '50 '
'degrees '
'C '
'/ '
'122 '
'degrees '
'F',
'@junos:celsius': '50'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 0 XR2 1 '
'Chip',
'status': 'OK',
'temperature': {
'#text': '80 '
'degrees '
'C '
'/ '
'176 '
'degrees '
'F',
'@junos:celsius': '80'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 1 TSen',
'status': 'OK',
'temperature': {
'#text': '36 '
'degrees '
'C '
'/ '
'96 '
'degrees '
'F',
'@junos:celsius': '36'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 1 Chip',
'status': 'OK',
'temperature': {
'#text': '44 '
'degrees '
'C '
'/ '
'111 '
'degrees '
'F',
'@junos:celsius': '44'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 1 XR2 0 '
'TSen',
'status': 'OK',
'temperature': {
'#text': '36 '
'degrees '
'C '
'/ '
'96 '
'degrees '
'F',
'@junos:celsius': '36'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 1 XR2 0 '
'Chip',
'status': 'OK',
'temperature': {
'#text': '60 '
'degrees '
'C '
'/ '
'140 '
'degrees '
'F',
'@junos:celsius': '60'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 1 XR2 1 '
'TSen',
'status': 'OK',
'temperature': {
'#text': '36 '
'degrees '
'C '
'/ '
'96 '
'degrees '
'F',
'@junos:celsius': '36'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XL 1 XR2 1 '
'Chip',
'status': 'OK',
'temperature': {
'#text': '59 '
'degrees '
'C '
'/ '
'138 '
'degrees '
'F',
'@junos:celsius': '59'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 0 TSen',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 0 Chip',
'status': 'OK',
'temperature': {
'#text': '62 '
'degrees '
'C '
'/ '
'143 '
'degrees '
'F',
'@junos:celsius': '62'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 1 TSen',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 1 Chip',
'status': 'OK',
'temperature': {
'#text': '57 '
'degrees '
'C '
'/ '
'134 '
'degrees '
'F',
'@junos:celsius': '57'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 2 TSen',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 2 Chip',
'status': 'OK',
'temperature': {
'#text': '51 '
'degrees '
'C '
'/ '
'123 '
'degrees '
'F',
'@junos:celsius': '51'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 3 TSen',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'FPC 0 XM 3 Chip',
'status': 'OK',
'temperature': {
'#text': '45 '
'degrees '
'C '
'/ '
'113 '
'degrees '
'F',
'@junos:celsius': '45'
}
}, {
'class': 'Temp',
'name': 'FPC 0 PCIe Switch '
'TSen',
'status': 'OK',
'temperature': {
'#text': '52 '
'degrees '
'C '
'/ '
'125 '
'degrees '
'F',
'@junos:celsius': '52'
}
}, {
'class': 'Temp',
'name': 'FPC 0 PCIe Switch '
'Chip',
'status': 'OK',
'temperature': {
'#text': '30 '
'degrees '
'C '
'/ '
'86 '
'degrees '
'F',
'@junos:celsius': '30'
}
}, {
'class': 'Temp',
'name': 'FPC 9 Intake',
'status': 'OK',
'temperature': {
'#text': '31 '
'degrees '
'C '
'/ '
'87 '
'degrees '
'F',
'@junos:celsius': '31'
}
}, {
'class': 'Temp',
'name': 'FPC 9 Exhaust A',
'status': 'OK',
'temperature': {
'#text': '48 '
'degrees '
'C '
'/ '
'118 '
'degrees '
'F',
'@junos:celsius': '48'
}
}, {
'class': 'Temp',
'name': 'FPC 9 Exhaust B',
'status': 'OK',
'temperature': {
'#text': '41 '
'degrees '
'C '
'/ '
'105 '
'degrees '
'F',
'@junos:celsius': '41'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 0 TCAM '
'TSen',
'status': 'OK',
'temperature': {
'#text': '46 '
'degrees '
'C '
'/ '
'114 '
'degrees '
'F',
'@junos:celsius': '46'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 0 TCAM '
'Chip',
'status': 'OK',
'temperature': {
'#text': '55 '
'degrees '
'C '
'/ '
'131 '
'degrees '
'F',
'@junos:celsius': '55'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 0 TSen',
'status': 'OK',
'temperature': {
'#text': '46 '
'degrees '
'C '
'/ '
'114 '
'degrees '
'F',
'@junos:celsius': '46'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 0 Chip',
'status': 'OK',
'temperature': {
'#text': '55 '
'degrees '
'C '
'/ '
'131 '
'degrees '
'F',
'@junos:celsius': '55'
}
}, {
'class': 'Temp',
'name': 'FPC 9 MQ 0 TSen',
'status': 'OK',
'temperature': {
'#text': '46 '
'degrees '
'C '
'/ '
'114 '
'degrees '
'F',
'@junos:celsius': '46'
}
}, {
'class': 'Temp',
'name': 'FPC 9 MQ 0 Chip',
'status': 'OK',
'temperature': {
'#text': '57 '
'degrees '
'C '
'/ '
'134 '
'degrees '
'F',
'@junos:celsius': '57'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 1 TCAM '
'TSen',
'status': 'OK',
'temperature': {
'#text': '41 '
'degrees '
'C '
'/ '
'105 '
'degrees '
'F',
'@junos:celsius': '41'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 1 TCAM '
'Chip',
'status': 'OK',
'temperature': {
'#text': '46 '
'degrees '
'C '
'/ '
'114 '
'degrees '
'F',
'@junos:celsius': '46'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 1 TSen',
'status': 'OK',
'temperature': {
'#text': '41 '
'degrees '
'C '
'/ '
'105 '
'degrees '
'F',
'@junos:celsius': '41'
}
}, {
'class': 'Temp',
'name': 'FPC 9 LU 1 Chip',
'status': 'OK',
'temperature': {
'#text': '47 '
'degrees '
'C '
'/ '
'116 '
'degrees '
'F',
'@junos:celsius': '47'
}
}, {
'class': 'Temp',
'name': 'FPC 9 MQ 1 TSen',
'status': 'OK',
'temperature': {
'#text': '41 '
'degrees '
'C '
'/ '
'105 '
'degrees '
'F',
'@junos:celsius': '41'
}
}, {
'class': 'Temp',
'name': 'FPC 9 MQ 1 Chip',
'status': 'OK',
'temperature': {
'#text': '47 '
'degrees '
'C '
'/ '
'116 '
'degrees '
'F',
'@junos:celsius': '47'
}
}, {
'class': 'Temp',
'name': 'ADC 9 Intake',
'status': 'OK',
'temperature': {
'#text': '32 '
'degrees '
'C '
'/ '
'89 '
'degrees '
'F',
'@junos:celsius': '32'
}
}, {
'class': 'Temp',
'name': 'ADC 9 Exhaust',
'status': 'OK',
'temperature': {
'#text': '42 '
'degrees '
'C '
'/ '
'107 '
'degrees '
'F',
'@junos:celsius': '42'
}
}, {
'class': 'Temp',
'name': 'ADC 9 ADC-XF1',
'status': 'OK',
'temperature': {
'#text': '49 '
'degrees '
'C '
'/ '
'120 '
'degrees '
'F',
'@junos:celsius': '49'
}
}, {
'class': 'Temp',
'name': 'ADC 9 ADC-XF0',
'status': 'OK',
'temperature': {
'#text': '59 '
'degrees '
'C '
'/ '
'138 '
'degrees '
'F',
'@junos:celsius': '59'
}
}, {
'class': 'Fans',
'comment': '2760 RPM',
'name': 'Fan Tray 0 Fan 1',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 0 Fan 2',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 0 Fan 3',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 0 Fan 4',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 0 Fan 5',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 0 Fan 6',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 1 Fan 1',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 1 Fan 2',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 1 Fan 3',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 1 Fan 4',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 1 Fan 5',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 1 Fan 6',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 2 Fan 1',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 2 Fan 2',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 2 Fan 3',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 2 Fan 4',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 2 Fan 5',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 2 Fan 6',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 3 Fan 1',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2400 RPM',
'name': 'Fan Tray 3 Fan 2',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 3 Fan 3',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 3 Fan 4',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2640 RPM',
'name': 'Fan Tray 3 Fan 5',
'status': 'OK'
}, {
'class': 'Fans',
'comment': '2520 RPM',
'name': 'Fan Tray 3 Fan 6',
'status': 'OK'
}]
}
}
|
# Declan Barr 19 Mar 2018
# Script that contains function sumultiply that takes two integer arguments and
# returns their product. Does this without the * or / operators
def sumultiply(x, y):
sumof = 0
for i in range(1, x+1):
sumof = sumof + y
return sumof
print(sumultiply(11, 13))
print(sumultiply(5, 123))
|
"""
link : https://leetcode.com/problems/koko-eating-bananas/
"""
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def condition(val):
hr = 0
for i in piles:
hr += (val + i - 1)//val
return hr <= h
left,right = 1,max(piles)
while left < right:
mid = (left + right)//2
if condition(mid):
right = mid
else:
left = mid + 1
return left
|
class Node:
def __init__(self, value, child, parent):
self._value = value
self._child = child
self._parent = parent
def get_value(self):
#Return the value of a node
return self._value
def get_child(self):
#Return the value of a node
return self._child
def get_parent(self):
#Return the parent of a node
return self._parent
def set_value(self, value):
#Change the value of a node
self._value = value
def set_child(self, child):
#Change the value of a node
self._child = child
def set_parent(self, parent):
#Change the parent reference
self._parent = parent |
# -*- coding: utf-8 -*-
"""
Created on Thu May 28 15:30:04 2020
@author: Christopher Cheng
"""
class Circle (object):
def __init__(self):
self.radius = 0
def change_radius(self, radius):
self.radius = radius
def get_radius (self):
return self.radius
class Rectangle(object):
# A rectangle object with a width and height
def __init__(self,length,width):
self.length = length
self.width = width
def set_length(self,length):
self.length = length
def set_width(self,width):
self.width = width
|
class AvatarPlugin:
"""
Abstract interface for all Avatar plugins
Upon start() and stop(), plugins are expected to register/unregister
their own event handlers by the means of :func:`System.register_event_listener`
and :func:`System.unregister_event_listener`
"""
def __init__(self, system):
self._system = system
def init(self, **kwargs):
assert(False) #Not implemented
def start(self, **kwargs):
assert(False) #Not implemented
def stop(self, **kwargs):
assert(False) #Not implemented
|
#!/usr/bin/env python
# encoding=utf-8
"""
inner_rpc.ir_exceptions
-----------------
该模块主要包括公共的异常定义
"""
class BaseError(Exception):
pass
class SocketError(BaseError):
pass
class SocketTimeout(SocketError):
pass
class DataError(BaseError):
pass
|
name = 'eric Pearson'
# Упражнение 3.
message = f'Hello {name}, would you like to learn some Python today?'
print(message)
# Упражнение 4.
message = f'Hello {name.lower()}, would you like to learn some Python today?'
print(message)
message = f'Hello {name.upper()}, would you like to learn some Python today?'
print(message)
message = f'Hello {name.title()}, would you like to learn some Python today?'
print(message)
# Упражнение 5.
message = f'Albert Einstein once said, "A person who never made a mistake never tried anything new."'
print(message)
# Упражнение 6.
famous_person = 'Albert Einstein'
message = f'{famous_person.title()} once said, "A person who never made a mistake never tried anything new."'
print(message)
# Упражнение 7.
famous_person = ' \t\nAlbert Einstein \t\n'
print(f'|{famous_person} once said, "A person who never made a mistake never tried anything new."|')
print(f'|{famous_person.lstrip()} once said, "A person who never made a mistake never tried anything new."|')
print(f'|{famous_person.rstrip()} once said, "A person who never made a mistake never tried anything new."|')
print(f'|{famous_person.strip()} once said, "A person who never made a mistake never tried anything new."|')
|
def find_sum(arr, s):
curr_sum = arr[0]
start = 0
n = len(arr) - 1
i = 1
while i <= n:
while curr_sum > s and start < i:
curr_sum = curr_sum - arr[start]
start += 1
if curr_sum == s:
return "Found between {} and {}".format(start, i - 1)
curr_sum = curr_sum + arr[i]
i += 1
return "Sum not found"
arr = [15, 2, 4, 8, 9, 5, 10, 23]
print(find_sum(arr, 6))
|
class HoloResponse:
def __init__(self, success, response=None):
self.success = success
if response != None:
self.response = response
|
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)
# Author: Bryan G
|
"""
Project name: SortingProblem
File name: BubbleSort.py
Description:
version:
Author: Jutraman
Email: jutraman@hotmail.com
Date: 04/07/2021 21:49
LastEditors: Jutraman
LastEditTime: 04/07/2021
Github: https://github.com/Jutraman
"""
def bubble_sort(array):
length = len(array)
for i in range(length):
for j in range(length - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array |
"""
ORM是django的核心思想, object-related-mapping对象-关系-映射
ORM核心就是操作数据库的时候不再直接操作sql语句,而是操作对象
定义一个类,类中有uid,username等类属型,sql语句insert修改的时候直接插入这个User对象
"""
# ORM映射实现原理,通过type修改类对象信息
# 定义这个元类metaclass
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
# name --> User
# bases --> object
# attrs --> {
# "uid" :('uid', "int unsigned"),
# "name": ('username', "varchar(30)"),
# "email": ('email', "varchar(30)"),
# "password": ('password', "varchar(30)"),
# "__init__": xxx,
# "save": xxx2,
# }
mappings = dict()
# 判断是否需要保存
for k, v in attrs.items():
# 判断是否是元组类型
if isinstance(v, tuple):
print('Found mapping: %s ==> %s' % (k, v))
mappings[k] = v
# 删除这些已经在字典中存储的属性
for k in mappings.keys():
attrs.pop(k) # 等于del attrs[k]
# 将之前的uid/name/email/password以及对应的对象引用、类名字
# attrs = {
# "__init__": xxxx,
# "save": xxxx2,
# "__mappings__": {
# "uid": ('uid', "int unsigned"),
# "name": ('username', "varchar(30)"),
# ""email: ('email', "varchar(30)"),
# "password": ('password', "varchar(30)")
# },
# "__table__": "User"
# }
attrs['__mappings__'] = mappings # 保存属性和列的映射关系
attrs['__table__'] = name # 假设表名和类名一致
return type.__new__(cls, name, bases, attrs)
class User(metaclass=ModelMetaclass):
uid = ('uid', "int unsigned")
name = ('username', "varchar(30)")
email = ('email', "varchar(30)")
password = ('password', "varchar(30)")
# 当指定元类之后,以上的类属性将不在类中,而是在__mappings__属性指定的字典中存储
# 以上User类中有
# __mappings__ = {
# "uid": ('uid', "int unsigned")
# "name": ('username', "varchar(30)")
# "email": ('email', "varchar(30)")
# "password": ('password', "varchar(30)")
# }
# __table__ = "User"
# 参数名是kwargs,不是**kwargs,**只是告诉解释器将传来的参数变为字典
# for循环遍历__new__返回的attrs字典,实现实例对象的属性和方法赋值
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
def save(self):
fields = [] # ["uid", "username"...]
args = [] #[12345, "laowang"...]
# 创建的实例对象中没有__mapping__,去类对象中找
# k --> uid, v --> 12345
for k, v in self.__mappings__.items():
fields.append(v[0])
args.append(getattr(self, k, None))
args_temp = list()
for temp in args:
if isinstance(temp, int):
# 判断如果是数字类型
args_temp.append(str(temp))
elif isinstance(temp, str):
# 判断如果是字符串类型
args_temp.append("""'%s'""" % temp)
# sql = 'insert into %s (%s) values (%s);' \
# % (self.__table__, ','.join(fields), ','.join([str(i) for i in args]))
# 使用",".join为每一个字段后都插入逗号分隔
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp))
print('SQL: %s' % sql)
# 抽取为基类,再创建User2这个类,就直接让其继承Model类
class Model(object, metaclass=ModelMetaclass):
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
def save(self):
fields = []
args = []
for k, v in self.__mappings__.items():
fields.append(v[0])
args.append(getattr(self, k, None))
args_temp = list()
for temp in args:
# 判断入如果是数字类型
if isinstance(temp, int):
args_temp.append(str(temp))
elif isinstance(temp, str):
args_temp.append("""'%s'""" % temp)
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(args_temp))
print('SQL: %s' % sql)
class User2(Model):
uid = ('uid', "int unsigned")
name = ('username', "varchar(30)")
email = ('email', "varchar(30)")
password = ('password', "varchar(30)")
def test01():
u = User(uid=12345, name='Michael', email='test@orm.org', password='my-pwd')
# print(u.__dict__)
u.save()
def test02():
list = ['12356', "laowang", "email"]
print(",".join(list))
def main():
# test01()
test02()
if __name__ == '__main__':
main()
|
def capture_high_res(filename):
return "./camerapi/tmp_large.jpg"
def capture_low_res(filename):
return "./camerapi/tmp_small.jpg"
def init():
return
def deinit():
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.