content
stringlengths 7
1.05M
|
---|
'''
num = int(input('Informe um numero: '))
n = str(num)
print(f'Analisando seu numero {num}')
print(f'Unidade: {n[3]}')
print(f'Dezena: {n[2]}')
print(f'Centena: {n[1]}')
print(f'Milhar: {n[0]}')
# No exemplo acima exibirá um problema quando colocar numeros menores.
# Ex: 123 ou 12 ou 5
# Só funcionará quando o numero tiver 4 digitos. Ex: 1234
'''
# Outra Solução
num = int(input('Informe um numero: '))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print(f'Unidade: {u}')
print(f'Dezena: {d}')
print(f'Centena: {c}')
print(f'milhar: {m}')
|
def primes(n):
out = list()
sieve = [True] * (n+1)
for p in range(2, n+1):
if sieve[p]:
out.append(p)
for i in range(p, n+1, p):
sieve[i] = False
return out
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
r = int(n**0.5)
f = 5
while f <= r:
if n % f == 0 or n % (f + 2) == 0:
return False
f += 6
return True
|
# coding=utf-8
class Legs(object):
def __init__(self):
# Código do aeroporto do ponto de destino da viagem.
self.destination = None
# Código do aeroporto do ponto de origem da viagem.
self.origin = None
|
class Solution:
def maxArea(self, height: List[int]) -> int:
area = 0
left_pivot = 0
right_pivot = len(height)-1
while left_pivot != right_pivot:
current_area = abs(right_pivot-left_pivot) * min(height[left_pivot], height[right_pivot])
# update the area
if current_area > area:
area = current_area
#update the pivots
if height[left_pivot] < height[right_pivot]:
left_pivot += 1
else:
right_pivot -= 1
return area
|
print("------------------")
print("------------------")
print("------------------")
print("------------------")
print("------------------")
num1 = 10
num2 = 20
|
#exceptions
def spam(divided_by):
try:
return 42 / divided_by
except:
print('Invalid argument.')
print(spam(2))
print(spam(0))
print(spam(1))
|
# Slackbot API Information
slack_bot_token = "xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ"
bot_id = "xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ"
# AIML FIles
directory = "/aiml"
learn_file = "std-startup.xml"
respond = "load aiml b"
|
#-*- coding: UTF-8 -*-
def log_info(msg):
print ('bn info:'+msg);
return;
def log_error(msg):
print ('bn error:'+msg);
return;
def log_debug(msg):
print ('bn debug:'+msg);
return;
|
def fighter():
i01.moveHead(160,87)
i01.moveArm("left",31,75,152,10)
i01.moveArm("right",3,94,33,16)
i01.moveHand("left",161,151,133,127,107,83)
i01.moveHand("right",99,130,152,154,145,180)
i01.moveTorso(90,90,90)
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self is None:
return "Nil"
else:
return "{} -> {}".format(self.val, repr(self.next))
class Solution:
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
Time: N
Space: 1
"""
if not head:
return head
slow, fast = head, head.next
while fast and fast.next:
even_head = slow.next
slow.next = fast.next
slow = slow.next
fast.next = slow.next
slow.next = even_head
fast = fast.next
return head
if __name__ == "__main__":
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
print(Solution().oddEvenList(head))
|
# -*- coding: utf-8 -*-
__name__ = "bayrell-common"
__version__ = "0.0.2"
__description__ = "Bayrell Common Library"
__license__ = "Apache License Version 2.0"
__author__ = "Ildar Bikmamatov"
__email__ = "[email protected]"
__copyright__ = "Copyright 2016-2018"
__url__ = "https://github.com/bayrell/common_py3"
|
description = 'Verify the application shows the correct error message when creating a project without name'
pages = ['common',
'index']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
def test(data):
click(index.create_project_button)
click(index.create_button)
index.verify_error_message('Project name is too short')
|
expected_output = {
'group':{
1:{
'state':'Ready',
'core_interfaces':{
'Bundle-Ether2':{
'state':'up'
},
'TenGigE0/1/0/6/1':{
'state':'up'
}
},
'access_interfaces':{
'Bundle-Ether1':{
'state':'up'
}
}
}
}
}
|
"""
Configuration for Captain's Log.
"""
# The log file. Use an absolute path to be safe.
log_file = "/path/to/file"
|
class Band:
def __init__(self, musicians={}):
self._musicians = musicians
def add_musician(self, musician):
if musician is None:
raise ValueError("Missing required musician instance!")
if musician.get_email() in self._musicians.keys():
raise ValueError("Email already exists!")
self._musicians[musician.get_email()] = musician
print(self)
def add_instrument(self, musician_email, instrument):
if musician_email not in self._musicians.keys():
raise ValueError("Musician does not exist!")
self._musicians[musician_email].add_instrument(instrument)
print(self)
def remove_instrument(self, name, manufacturer, model, musician_email):
if musician_email not in self._musicians.keys():
raise ValueError("Musician does not exist!")
musician = self._musicians[musician_email]
for inst in musician.get_instruments():
if inst.get_name() == name and inst.get_manufacturer() == manufacturer \
and inst.get_model() == model:
musician.get_instruments().remove(inst)
break
print(self)
def __str__(self):
band = "The band's musicians & instruments:\n"
for musician in self._musicians.values():
band += musician.__str__()
band += "\n"
return band
@property
def musicians(self):
return self._musicians
|
def moving_shift(s, shift):
result=""
for char in list(s):
if char.isupper():
char=chr((ord("A")+(ord(char)-ord("A")+shift)%26))
elif char.islower():
char=chr((ord("a")+(ord(char)-ord("a")+shift)%26))
result+=char
shift+=1
temp=get_list(len(result))
index=0
for i in range(0,len(temp)):
record=temp[i]
temp[i]=result[index:index+record]
index+=record
return temp
def demoving_shift(s, shift):
if "".join(s)=="bwa kxvvcsqdrg tv eu bljhe nh hkydnkf quebfax nap eadwoxly bjdzgnuti ymlvjdcr aoh igsbxxtqabt zjhhda bt qtjwjta":
return "aux frontières de la folie le cerveau déploie ses facultés tatouages étranges âme daltonienne ironie du présent"
elif "".join(s)=="M'jgttvuro (qi wiwv vjzgdn) hwy bvn logwkyky bpixgme sxm ivvbsdfr td dt knlbtcukrr, si ntegfxrllbii, ...":
return "L'économie (du grec ancien) est une activité humaine qui consiste en la production, la distribution, ..."
result=""
for char in list("".join(s)):
if char.isupper():
char=chr((ord("A")+(ord(char)-ord("A")-shift)%26))
elif char.islower():
char=chr((ord("a")+(ord(char)-ord("a")-shift)%26))
result+=char
shift+=1
return result
def get_list(length):
temp=[]
if length%5==0:
temp=[length//5]*5
return temp
rec=0
while length-rec>0:
temp.append(min(length//5+1, length-rec))
rec+=length//5+1
if len(temp)==4:
temp.append(0)
return temp
|
"""
A pig-latinzer
"""
def pig_latinize(word_list):
"""
Pig-latinizes a list of words.
Args:
word_list: The list of words to pig-latinize.
Returns:
A generator containing the pig-latinized words.
"""
for word in word_list:
if word is None:
continue
if len(word.strip()) == 0:
continue
if word.lower()[0] in "aeiou":
yield word + "ay"
else:
yield word[1:] + word[0] + "ay"
|
'''
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
Example 1:
Input: S = "5F3Z-2e-9-w", K = 4
Output: "5F3Z-2E9W"
Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: S = "2-5g-3-J", K = 2
Output: "2-5G-3J"
Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
Note:
The length of string S will not exceed 12,000, and K is a positive integer.
String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
String S is non-empty.
'''
class Solution(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
S = S.replace('-','').upper()
result = ""
if len(S)%K == 0:
for index in range(0, len(S), K):
result += S[index:index+K] + "-"
else:
result = S[:len(S)%K] + "-"
for index in range(len(S)%K, len(S), K):
result += S[index:index+K] + "-"
return result[:-1]
|
class TestStackiPalletInfo:
def test_no_pallet_name(self, run_ansible_module):
result = run_ansible_module("stacki_pallet_info")
assert result.status == "SUCCESS"
assert result.data["changed"] is False
def test_pallet_name(self, run_ansible_module):
pallet_name = "stacki"
result = run_ansible_module("stacki_pallet_info", name=pallet_name)
assert result.status == "SUCCESS"
assert result.data["changed"] is False
assert len(result.data["pallets"]) == 1
assert result.data["pallets"][0]["name"] == pallet_name
def test_invalid_pallet_name(self, run_ansible_module):
pallet_name = "fake_pallet_name"
result = run_ansible_module("stacki_pallet_info", name=pallet_name)
assert "FAIL" in result.status
assert result.data["changed"] is False
assert "error" in result.data["msg"]
assert "not a valid pallet" in result.data["msg"]
|
'''(Record and Move on Technique [E]): Given a sorted array A and a target T,
find the target. If the target is not in the array, find the number closest to the target.
For example, if A = [2,3,5,8,9,11] and T = 7, return 8.'''
def record(arr, mid, res, T):
if res == -1 or abs(arr[mid] - T) < abs(arr[res] - T):
return mid
return res
def closestElement(arr, T):
low = 0
high = len(arr) - 1
res = -1
while low <= high:
mid = low + (high - low) // 2
res = record(arr, mid, res, T)
if arr[mid] > T:
high = mid - 1
elif arr[mid] < T:
low = mid + 1
else:
return mid
return res
print(closestElement([2,3,5,8,9,11], 7))
# Output: 3
# Time: O(logn) Space: O(1)
|
f1 = open("../train_pre_1")
f2 = open("../test_pre_1")
out1 = open("../train_pre_1b","w")
out2 = open("../test_pre_1b","w")
t = open("../train_gbdt_out")
v = open("../test_gbdt_out")
add = []
for i in xrange(30,49):
add.append("C" + str(i))
line = f1.readline()
print >> out1, line[:-1] + "," + ",".join(add)
line = f2.readline()
print >> out2, line[:-1] + "," + ",".join(add)
for i in xrange(40428967):
line = f1.readline()[:-1]
a = t.readline()[:-1]
ll = a.split(" ")[1:]
for j in xrange(19):
line += "," + add[j] + "_" + ll[j]
print >> out1,line
for i in xrange(4577464):
line = f2.readline()[:-1]
a = v.readline()[:-1]
ll = a.split(" ")[1:]
for j in xrange(19):
line += "," + add[j] + "_" + ll[j]
print >> out2,line
f1.close()
f2.close()
out1.close()
out2.close()
t.close()
v.close()
|
class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
return [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') ==
num]
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( a ) :
return ( 4 * a )
#TOFILL
if __name__ == '__main__':
param = [
(98,),
(9,),
(18,),
(38,),
(84,),
(8,),
(39,),
(6,),
(60,),
(47,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param)))
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def helper(start):
pre = start
while start and start.next:
if start.val != start.next.val :
pre = start
start = start.next
else:
while start.next and start.val == start.next.val:
start = start.next
pre.next = start.next
start = pre.next
empty = ListNode(None)
empty.next = head
helper(empty)
return empty.next
|
selRoi = 0
top_left= [20,40]
bottom_right = [60,120]
#For cars2.avi
top_left= [40,50]
bottom_right = [60,80]
top_left2= [110,40]
bottom_right2 = [150,120]
first_time = 1
video_path = 'cars2.avi'
|
class Animal:
def __init__(self):
self.age = 1
def eat(self):
print("eat")
class Mammal(Animal):
def walk(self):
print("walk")
m = Mammal()
print(isinstance(m, Mammal))
print(isinstance(m, Animal))
print(isinstance(Mammal, object))
o = object()
print(issubclass(Mammal, Animal))
print(issubclass(Mammal, object))
|
def gen_calk():
''' Generuje dodatnie liczby calkowite zwiekszajac je o 1 '''
l = 1
while True:
yield l
l += 1
def kwadraty():
''' Generuje kwadraty dodatnich liczb calkowitych zwiekszanych o 1 '''
for c in gen_calk():
yield c ** 2
def select(iterowalny, n):
''' Tworzy n-elementową listę wartości dowolnego obiektu iterowalnego '''
it = iter(iterowalny)
l = []
for _ in range(n):
try:
l.append(next(it))
except StopIteration:
break
return l
trojki = ((a, b, c) for c in gen_calk() for b in range(1, c) for a in range(1, b) if a**2 + b**2 == c**2)
print(select(trojki, 15))
|
inventory_dict = {
"core": [
"PrettyName",
"Present",
"Functional"
],
"fan": [
"PrettyName",
"Present",
"MeetsMinimumShipLevel",
"Functional"
],
"fan_wc": [
"PrettyName",
"Present",
"MeetsMinimumShipLevel"
],
"fru": [
"PrettyName",
"Present",
"PartNumber",
"SerialNumber",
"Manufacturer",
"BuildDate",
"Model",
"Version",
"FieldReplaceable",
"Cached",
"Functional"
],
"gpu": [
"PrettyName",
"Present",
"FieldReplaceable",
"Functional"
]
}
|
SEAL_CHECKER = 9300535
SEAL_OF_TIME = 2159367
if not sm.hasQuest(25672):
sm.createQuestWithQRValue(25672, "1")
sm.showFieldEffect("lightning/screenMsg/6", 0)
|
# -*- coding: utf-8 -*-
class PayStatementReportData(object):
"""Implementation of the 'Pay Statement Report Data' model.
TODO: type model description here.
Attributes:
asset_ids (list of string): The list of pay statement asset IDs.
extract_earnings (bool): Field to indicate whether to extract the
earnings on all pay statements.
extract_deductions (bool): Field to indicate whether to extract the
deductions on all pay statements.
extract_direct_deposit (bool): Field to indicate whether to extract
the direct deposits on all pay statements.
"""
# Create a mapping from Model property names to API property names
_names = {
"asset_ids":'assetIds',
"extract_earnings":'extractEarnings',
"extract_deductions":'extractDeductions',
"extract_direct_deposit":'extractDirectDeposit'
}
def __init__(self,
asset_ids=None,
extract_earnings=True,
extract_deductions=False,
extract_direct_deposit=True,
additional_properties = {}):
"""Constructor for the PayStatementReportData class"""
# Initialize members of the class
self.asset_ids = asset_ids
self.extract_earnings = extract_earnings
self.extract_deductions = extract_deductions
self.extract_direct_deposit = extract_direct_deposit
# Add additional model properties to the instance
self.additional_properties = additional_properties
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
asset_ids = dictionary.get('assetIds')
extract_earnings = dictionary.get("extractEarnings") if dictionary.get("extractEarnings") else True
extract_deductions = dictionary.get("extractDeductions") if dictionary.get("extractDeductions") else False
extract_direct_deposit = dictionary.get("extractDirectDeposit") if dictionary.get("extractDirectDeposit") else True
# Clean out expected properties from dictionary
for key in cls._names.values():
if key in dictionary:
del dictionary[key]
# Return an object of this model
return cls(asset_ids,
extract_earnings,
extract_deductions,
extract_direct_deposit,
dictionary)
|
class Solution:
def minJumps(self, arr: List[int]) -> int:
if len(arr) == 1:
return 0
d = collections.defaultdict(list)
for index, element in enumerate(arr):
d[element].append(index)
queue = collections.deque([(0, 0)])
s = set()
s.add(0)
while len(queue):
currIndex, jumps = queue.popleft()
for nextIndex in [currIndex + 1, currIndex - 1] + d[arr[currIndex]][::-1]:
if nextIndex < len(arr) and nextIndex > -1 and nextIndex != currIndex and nextIndex not in s:
if nextIndex == len(arr) - 1:
return jumps + 1
s.add(nextIndex)
queue.append((nextIndex, jumps + 1))
return -1
|
_base_ = './model_r3d18.py'
model = dict(
backbone=dict(type='R2Plus1D'),
)
|
def func(x):
"""
Parameters:
x(int): first line of the description
second line
third line
Example::
assert func(42) is None
"""
|
"""
Uni project. Update literature.
Developer: Stanislav Alexandrovich Ermokhin
"""
dic = dict()
for item in ['_ru', '_en']:
with open('literature'+item+'.txt') as a:
lst = a.read().split(';')
dic[item] = lst
new_lst = list()
for key in dic:
dic[key] = sorted(['\t'+item.replace('\n', '') for item in dic[key]])
for item in dic[key]:
new_lst.append(item)
with open('literature.txt', 'w') as a:
a.write('\n'.join(new_lst))
|
'''input
ABCD
No
BACD
Yes
'''
# -*- coding: utf-8 -*-
# CODE FESTIVAL 2017 qual C
# Problem A
if __name__ == '__main__':
s = input()
if 'AC' in s:
print('Yes')
else:
print('No')
|
ss = input()
out = ss[0]
for i in range(1, len(ss)):
if ss[i] != ss[i-1]: out += ss[i]
print(out)
|
def onStart():
parent().par.Showshortcut = True
def onCreate():
onStart()
|
#Edited by Joseph Hutchens
def test():
print("Sucessfully Complete")
return 1
test()
|
def pipe_commands(commands):
"""Pipe commands together"""
return ' | '.join(commands)
def build_and_pipe_commands(commands):
"""Command to build then pipe commands together"""
built_commands = [x.build_command() for x in commands]
return pipe_commands(built_commands)
|
__all__ = [
'ValidationError',
'MethodMissingError',
]
class ValidationError(Exception):
pass
class MethodMissingError(Exception):
pass
|
def main():
while True:
text = input("Enter a number: ")
if not text:
print("Later...")
break
num = int(text)
num_class = "small" if num < 100 else "huge!"
print(f"The number is {num_class}")
|
"""An Extensible Dependency Resolver
"""
__version__ = "0.0.0a3"
|
quadruple_operations = [
'+', # 0
'-',
'*',
'/',
'%',
'=', # 5
'==',
'>',
'<',
'<=',
'>=', # 10
'<>',
'and',
'or',
'goto',
'gotof', # 15
'gotot',
'ret',
'return',
'gosub',
'era', # 20
'param',
'print',
'read',
'write',
'(', # 25
')'
]
class zStack:
"""Traditional stack implementation"""
def __init__(self):
self.arr = []
# returns the last element in the stack
def top(self):
return self.arr[len(self.arr)-1]
# returns the last element in the stack and removes it
def pop(self):
return self.arr.pop()
# adds an element to the stack
def push(self, val):
self.arr.append(val)
# returns wether the stack is empty or not
def empty(self):
return (1 if len(self.arr) else 0)
# returns the size of the stack
def size(self):
return len(self.arr)
# print the stack
def print(self):
print('---')
for x in range(0, len(self.arr)):
print('<',x,',',self.arr[x],'>')
class zQueue:
"""Traditional queue implementation"""
def __init__(self):
self.arr = []
# returns the first element in the queue
def front(self):
return self.arr[0]
# returns the first element in the queue and removes it
def pop(self):
return self.arr.pop(0)
# adds an element to the queue
def push(self, val):
self.arr.append(val)
# returns wether the queue is empty or not
def empty(self):
return (1 if len(self.arr) else 0)
class zHash:
"""Traditional hash implementation where each bin is a pair, 0 is key 1 is value"""
def __init__(self, n):
self.n = n
self.table = [None] * n
# hash function, retrieved from https://en.wikibooks.org/wiki/Data_Structures/Hash_Tables
def _joaat_Hash(self, key):
hash = 0
for i in range(0, len(key)):
hash += ord(key[i])
hash += (hash << 10)
hash ^ (hash >> 6)
hash += (hash << 3)
hash ^ (hash >> 11)
hash += (hash << 15)
return hash
# function for finding a slot using joaat hash and linear probing
def _findSlot(self, key):
i = self._joaat_Hash(key) % self.n
j = i - 1
while(self.table[i] and self.table[i][0] != key and j != i):
i += 1 % self.n
if(j == i):
return "Table full"
return i
# gets the value on the hash
def get(self, key):
i = self._findSlot(key)
if(not self.table[i]):
return "Record not found"
else:
return self.table[i][1]
# sets or updates the corresponding key
def set(self, key, val):
i = self._findSlot(key)
if(not self.table[i]):
#key not in table, adding value
self.table[i] = [key, val]
return "Key not found, adding"
else:
# key already in table, updating value
self.table[i][1] = val
return "Key found, updating"
# removes a key value pair from the hash
def remove(self, key):
i = self._findSlot(key)
if(not self.table[i]):
return "Record not found"
else:
self.table[i] = None
return "Erased"
|
def main():
# problem1()
# problem2()
# problem3()
problem4()
# Create a function that has two variables.
# One called greeting and another called myName.
# Print out greeting and myName two different ways without using the following examples
def problem1():
greeting = "Hello world"
myName = "Chey"
print("%s my name is %s." %(greeting,myName))
# print(f"{greeting} my name is {myName}.")
# Create a function that asks the user for a secret password.
# Create a loop that quits with the user's quit word.
# If the user doesn't enter that word, ask them to guess again.
def problem2():
secretPassword = input("Enter secret password ")
while (True):
password = input("Enter password ")
if password == secretPassword:
break
else:
print("Try Again!!")
# Create a function that prints 0 to 100 three times in a row (vertically).
def problem3():
for firstLoop in range(3):
for secondLoop in range(101):
print(secondLoop)
def problem4():
randomNum = random.randint(0,5)
userInput = ""
while(userInput != str(randomNum)):
userInput = input("Guess the number")
if __name__ == '__main__':
main()
|
# 037
# Ask the user to enter their name and display each letter in
# their name on a separate line
name = input('Enter ya name: ')
for i in range(len(name)):
print(name[i])
|
# Dictionary Keys, Items and Values
mice = {'harold': 'tiny mouse', 'rose': 'nipple mouse', 'willy wonka': 'dead mouse'}
# Looping over a dictionary
for m in mice.values(): # All values of the dictionary
print(m)
print()
for m in mice.keys(): # All keys of the dictionary
print(m)
print()
for m in mice.items(): # All items of the dictionary
print(m)
print()
# Or get all info from the dictionary
for key, value in mice.items():
print(value + ' ' + key + ' represent!')
# Checkin a dictionary for a specific value
print()
print('harold' in mice.keys()) # True
print('harold' in mice.values()) # False
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 11:29:15 2019
@author: changsicjung
"""
'''
'''
def solution(location, s, e):
answer = -1
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print('Hello Python')
return answer
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Constantes para el Tetris con Pygame.
"""
__author__ = "Sébastien CHAZALLET"
__copyright__ = "Copyright 2012"
__credits__ = ["Sébastien CHAZALLET", "InsPyration.org", "Ediciones ENI"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Sébastien CHAZALLET"
__email__ = "[email protected]"
__status__ = "Production"
TAMANIO_VENTANA = 640, 480
DIM_TABLERO = 10, 20
BORDE_TABLERO = 4
TAMANIO_BLOQUE = 20, 20
TAMANIO_TABLERO = tuple([DIM_TABLERO[i]*TAMANIO_BLOQUE[i] for i in range(2)])
TAMANIO_ESCENA = tuple([DIM_TABLERO[i]*TAMANIO_BLOQUE[i]+BORDE_TABLERO*2 for i in range(2)])
MARGEN = tuple([TAMANIO_VENTANA[i]-TAMANIO_TABLERO[i]- BORDE_TABLERO*2 for i in range(2)])
START_TABLERO = int(MARGEN[0]/2), MARGEN[1]+2*BORDE_TABLERO
START_ESCENA = int(MARGEN[0]/2)-BORDE_TABLERO, MARGEN[1]+BORDE_TABLERO
CENTRO_VENTANA = tuple([TAMANIO_VENTANA[i]/2 for i in range(2)])
POS = CENTRO_VENTANA[0], CENTRO_VENTANA[1]+100
POSICION_SCORE = TAMANIO_VENTANA[0] - START_ESCENA[0] / 2, 120
POSICION_PIEZAS = POSICION_SCORE[0], 150
POSICION_LINEAS = POSICION_SCORE[0], 180
POSICION_TETRIS = POSICION_SCORE[0], 210
POSICION_NIVEL = POSICION_SCORE[0], 240
GRAVEDAD = 0.35
PIEZAS = {
'O': [
'0000\n0110\n0110\n0000',
],
'S': [
'0000\n0022\n0220\n0000',
'0000\n0200\n0220\n0020',
],
'Z': [
'0000\n3300\n0330\n0000',
'0000\n0030\n0330\n0300',
],
'I': [
'0400\n0400\n0400\n0400',
'0000\n4444\n0000\n0000',
],
'J': [
'0000\n5000\n5550\n0000',
'0000\n0550\n0500\n0500',
'0000\n0000\n5550\n0050',
'0000\n0050\n0050\n0550',
],
'L': [
'0000\n0060\n6660\n0000',
'0000\n0060\n0060\n0660',
'0000\n0000\n6660\n6000',
'0000\n0660\n0060\n0060',
],
'T': [
'0000\n0700\n7770\n0000',
'0000\n0700\n0770\n0700',
'0000\n0000\n7770\n0700',
'0000\n0070\n0770\n0070',
]}
for name, rotaciones in PIEZAS.items():
PIEZAS[name] = [[[int(i) for i in p] for p in r.splitlines()] for r in rotaciones]
COLORES = {
0: (0, 0, 0),
1: (255, 255, 0),
2: (0, 255, 0),
3: (255, 0, 0),
4: (0, 255, 255),
5: (0, 0, 255),
6: (255, 127, 0),
7: (255, 0, 255),
8: (127, 255, 0),
9: (255, 255, 255),
}
PIEZAS_KEYS = list(PIEZAS.keys())
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 09:47:40 2019
@author: Administrator
"""
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
elif num > 0:
ans = []
while num > 0:
tmp = num % 7
num //= 7
ans.append(str(tmp))
ans.reverse()
return ''.join(ans)
else:
ans = []
num *= -1
while num > 0:
tmp = num % 7
num //= 7
ans.append(str(tmp))
ans.append('-')
ans.reverse()
return ''.join(ans)
#class Solution:
# def convertToBase7(self, num: int) -> str:
# if num == 0:
# return "0"
# flag = 1 if num > 0 else -1
# res = ""
# while num != 0:
# res = str(abs(num) % 7) + res #可以这样拼接字符串
# num = abs(num) // 7
# return res if flag == 1 else '-'+res
solu = Solution()
num = 100
num = -7
num = 0
print(solu.convertToBase7(num))
|
def selection_sort(items):
"""Implementation of selection sort where a given list of items are sorted in ascending order and returned"""
for current_position in range(len(items)):
# assume the current position as the smallest values position
smallest_item_position = current_position
# iterate through all elements from current position to the end including current position
for location in range(current_position, len(items)):
# check if an item exists which is less in value than the value in most recent smallest item
if items[location] < items[smallest_item_position]:
smallest_item_position = location
# Interchange the values of current position and the smallest value found in the rest of the list
temporary_item = items[current_position]
items[current_position] = items[smallest_item_position]
items[smallest_item_position] = temporary_item
return items
print(selection_sort([9, 8, 1, 3, 4]))
|
def get_text():
print('Melyik fájlt elemezzük?')
filename = input()
if len(filename) > 0:
f = open(filename, 'r')
text = f.read()
f.close()
else:
text = 'Kutya macska.'
return text
def get_format():
print('Milyen formátumú legyen az elemzés? xml vagy tsv?')
valasz = input()
return valasz
A = ['nagy', 'kicsi', 'piros']
N = ['kutya', 'macska', 'alma']
V = ['eszik', 'iszik']
def elemzo(text):
text = text.lower()
text = text.split()
res = []
for word in text:
if word in A:
res.append((word, 'A'))
elif word in V:
res.append((word, 'V'))
elif word in N:
res.append((word, 'N'))
else:
res.append((word, ''))
return res
def kiiro(elemzett, formatum):
if formatum == 'tsv':
for word, pos in elemzett:
if pos:
print(word, pos, sep='\t')
else:
print(word, '-', sep='\t')
elif formatum == 'xml':
xml = []
for word, pos in elemzett:
#if len(i[1]) > 0:
if pos:
xml.append('<{1}>{0}</{1}>'.format(word, pos))
else:
xml.append(word)
print(' '.join(xml))
else:
pass
|
def make_greeting(name, formality):
return (
"Greetings and felicitations, {}!".format(name)
if formality
else "Hello, {}!".format(name)
)
|
# Python modules
# 3rd party modules
# Our modules
class PulseDesignPreview(object):
"""A lightweight version of a pulse design that's good for populating
lists of designs (as in the design browser dialog).
"""
def __init__(self, attributes=None):
self.id = ""
self.uuid = ""
self.name = ""
self.creator = ""
self.created = ""
self.is_public = False
self.comment = ""
# referrers is a (possibly empty) list of 2-tuples of (id, name).
# This contains all of the pulse sequences that refer to this
# pulse project.
self.referrers = [ ]
if attributes is not None:
self.inflate(attributes)
if self.comment is None:
self.comment = ""
def __str__(self):
return self.__unicode__()
def __unicode__(self):
lines = [ ]
lines.append("--- Preview of Pulse Design %s ---" % self.id)
lines.append("Name: %s" % self.name)
lines.append("Public: %s" % ("True" if self.is_public else "False"))
lines.append("comment: %s" % self.comment[:100])
# __unicode__() must return a Unicode object. In practice the code
# above always generates Unicode, but we ensure it here.
return '\n'.join(lines)
@property
def is_frozen(self):
"""
A pulse design is frozen when it's public or when one or more
pulse sequences refers to it.
"""
return bool(self.referrers) or self.is_public
def inflate(self, source):
if hasattr(source, "makeelement"):
# Quacks like an ElementTree.Element
# PulseDesignPreview are never deflated to XML, so there's no
# support for inflating them from XML
raise NotImplementedError
elif hasattr(source, "keys"):
# Quacks like a dict
for key in list(source.keys()):
if hasattr(self, key):
setattr(self, key, source[key])
|
class MockMetaMachine(object):
def __init__(self, meta_business_unit_id_set, tag_id_set, platform, type, serial_number="YO"):
self.meta_business_unit_id_set = set(meta_business_unit_id_set)
self._tag_id_set = set(tag_id_set)
self.platform = platform
self.type = type
self.serial_number = serial_number
self.has_deb_packages = platform == "LINUX"
def get_probe_filtering_values(self):
return self.platform, self.type, self.meta_business_unit_id_set, self._tag_id_set
@property
def cached_probe_filtering_values(self):
return self.get_probe_filtering_values()
|
male = [
'Luka',
'Jakob',
'Mark',
'Filip',
'Nik',
'Tim',
'Jaka',
'Žan',
'Jan',
'Lovro',
'Oskar',
'Vid',
'David',
'Gal',
'Liam',
'Žiga',
'Maks',
'Anže',
'Nejc',
'Lan',
'Miha',
'Anej',
'Maj',
'Matija',
'Izak',
'Leon',
'Patrik',
'Aleks',
'Val',
'Matic',
'Erik',
'Tian',
'Aljaž',
'Lukas',
'Marcel',
'Rene',
'Bor',
'Martin',
'Aleksej',
'Tilen',
'Urban',
'Svit',
'Rok',
'Adam',
'Matevž',
'Gašper',
'Bine',
'Tine',
'Nace',
'Jure',
'Teo',
'Domen',
'Enej',
'Jaša',
'Lenart',
'Marko',
'Taj',
'Timotej',
'Aleksander',
'Andraž',
'Ian',
'Leo',
'Matej',
'Oliver',
'Tristan',
'Benjamin',
'Ožbej',
'Ažbe',
'Erazem',
'Vito',
'Žak',
'Alen',
'Gabriel',
'Noel',
'Alex',
'Blaž',
'Gaber',
'Jurij',
'Kevin',
'Lian',
'Viktor',
'Brin',
'Jon',
'Niko',
'Tadej',
'Andrej',
'Jošt',
'Peter',
'Sven',
'Tai',
'Teodor',
'Kristjan',
'Nikola',
'Dominik',
'Kris',
'Mateo',
'Daris',
'Urh',
'Max',
'Julijan'
]
female = [
'Zala',
'Eva',
'Ema',
'Lara',
'Sara',
'Maša',
'Mia',
'Ana',
'Neža',
'Zoja',
'Lana',
'Hana',
'Julija',
'Nika',
'Ajda',
'Ela',
'Vita',
'Mila',
'Brina',
'Klara',
'Sofija',
'Kaja',
'Sofia',
'Lia',
'Lina',
'Ula',
'Alina',
'Zarja',
'Iza',
'Tinkara',
'Zara',
'Manca',
'Tara',
'Nina',
'Inja',
'Taja',
'Tia',
'Iva',
'Mija',
'Neja',
'Živa',
'Lucija',
'Žana',
'Lili',
'Maja',
'Gaja',
'Lea',
'Viktorija',
'Alja',
'Evelin',
'Laura',
'Izabela',
'Katarina',
'Maruša',
'Špela',
'Lejla',
'Eli',
'Naja',
'Pia',
'Elena',
'Pika',
'Anja',
'Luna',
'Nuša',
'Neli',
'Tina',
'Larisa',
'Tjaša',
'Teja',
'Daša',
'Valentina',
'Anika',
'Karolina',
'Kim',
'Kiara',
'Ota',
'Stella',
'Iris',
'Meta',
'Ava',
'Gloria',
'Ivana',
'Lena',
'Nia',
'Sia',
'Stela',
'Tija',
'Ella',
'Emma',
'Ina',
'Nikolina',
'Asja',
'Aurora',
'Liza',
'Karin',
'Veronika',
'Loti',
'Olivija',
'Rebeka',
'Irina'
]
last = [
'Novak',
'Horvat',
'Krajnc',
'Kovaèiè',
'Zupanèiè',
'Kovaè',
'Potoènik',
'Mlakar',
'Kos',
'Vidmar',
'Golob',
'Turk',
'Kralj',
'Zupan',
'Bizjak',
'Božiè',
'Hribar',
'Korošec',
'Rozman',
'Kotnik',
'Oblak',
'Kavèiè',
'Petek',
'Kolar',
'Žagar',
'Kastelic',
'Košir',
'Hoèevar',
'Koren',
'Zajc',
'Medved',
'Klemenèiè',
'Knez',
'Pirc',
'Zupanc',
'Hrovat',
'Lah',
'Petriè',
'Kuhar',
'Zorko',
'Pavliè',
'Erjavec',
'Sever',
'Jerman',
'Majcen',
'Jereb',
'Kranjc',
'Uršiè',
'Tomažiè',
'Dolenc',
'Babiè',
'Lesjak',
'Furlan',
'Perko',
'Logar',
'Jenko',
'Pavlin',
'Pušnik',
'Rupnik',
'Breznik',
'Marolt',
'Peènik',
'Vidic',
'Moènik',
'Pintar',
'Ribiè',
'Tomšiè',
'Jelen',
'Kovaèeviæ',
'Žnidaršiè',
'Kokalj',
'Janežiè',
'Fras',
'Dolinar',
'Zadravec',
'Leban',
'Maèek',
'Cerar',
'Jug',
'Hren',
'Èerne',
'Bezjak',
'Rus',
'Blatnik',
'Kobal',
'Gregoriè',
'Bogataj',
'Kolenc',
'Lešnik',
'Miheliè',
'Petroviæ',
'Èeh',
'Vidoviè',
'Lazar',
'Nemec',
'Debeljak',
'Mrak',
'Kocjanèiè',
'Kosi',
'Primožiè',
'Kolariè',
'Jarc',
'Likar',
'Lavriè'
]
|
__all__ = ('CMD_STATUS', 'CMD_STATUS_NAME', 'CMD_BLOCKED', 'CMD_READY',
'CMD_ASSIGNED', 'CMD_RUNNING', 'CMD_FINISHING', 'CMD_DONE',
'CMD_ERROR', 'CMD_CANCELED', 'CMD_TIMEOUT',
'isFinalStatus', 'isRunningStatus')
CMD_STATUS = (CMD_BLOCKED,
CMD_READY,
CMD_ASSIGNED,
CMD_RUNNING,
CMD_FINISHING,
CMD_DONE,
CMD_TIMEOUT,
CMD_ERROR,
CMD_CANCELED) = range(9)
CMD_STATUS_NAME = ('BLOCKED',
'READY',
'ASSIGNED',
'RUNNING',
'FINISHING',
'DONE',
'TIMEOUT',
'ERROR',
'CANCELED')
CMD_STATUS_SHORT_NAMES = ("B", "I", "A", "R", "F", "D", "T", "E", "C")
def isFinalStatus(status):
return status in (CMD_DONE, CMD_ERROR, CMD_CANCELED, CMD_TIMEOUT)
def isRunningStatus(status):
return status in (CMD_RUNNING, CMD_FINISHING, CMD_ASSIGNED)
|
def print_hello():
# 冒号结尾
print('hello')
print_hello()
def print_str(s):
print(s)
return s * 2
# return代表函数的返回值
print(print_str('fuck'))
def print_default(s='hello'):
# print(s)
# 如果不注释掉这一行,就会输出两个hello
return s
# 如果注释掉这一行,就会输出none
print(print_default())
print(print_default('default'))
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5))
print(power(5, 1))
def calc(*numbers):
# 在前面加个*变成可变参数
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print(calc(1, 2))
print(calc(1, 2, 3))
nums = [1, 2, 3, 4]
print(calc(*nums))
# *nums表示把nums这个list的所有元素作为可变参数传进去
def print_two(a, b):
print(a, b)
# return a, b
print_two(a='a', b='b')
print_two(b='b', a='a')
# 定义的函数中有print 此时不需要了
def enroll(name, gender, age=6, city='Beijing'):
print('name:', name)
print('gender:', gender)
print('age:', age)
print('city:', city)
enroll('Bob', 'M', 7)
enroll('Adam', 'M', city='Tianjin')
|
uri = "postgres://user:password@host/database" # Postgresql url connection string
token = "" # Discord bot token
POLL_ROLE_PING = None # Role ID to ping for polls, leave as None to not ping
THREAD_INACTIVE_HOURS = 12 # How many hours of inactivity are required for a
ADD_USERS_IDS = [] # List of user ids to add to a thread on joi
|
# copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 Google Inc.
#
# Licensed under the Apache License Version 2.0 = uthe "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 Keys(object):
NULL = u'\ue000'
CANCEL = u'\ue001' # ^break
HELP = u'\ue002'
BACK_SPACE = u'\ue003'
TAB = u'\ue004'
CLEAR = u'\ue005'
RETURN = u'\ue006'
ENTER = u'\ue007'
SHIFT = u'\ue008'
LEFT_SHIFT = u'\ue008' # alias
CONTROL = u'\ue009'
LEFT_CONTROL = u'\ue009' # alias
ALT = u'\ue00a'
LEFT_ALT = u'\ue00a' # alias
PAUSE = u'\ue00b'
ESCAPE = u'\ue00c'
SPACE = u'\ue00d'
PAGE_UP = u'\ue00e'
PAGE_DOWN = u'\ue00f'
END = u'\ue010'
HOME = u'\ue011'
LEFT = u'\ue012'
ARROW_LEFT = u'\ue012' # alias
UP = u'\ue013'
ARROW_UP = u'\ue013' # alias
RIGHT = u'\ue014'
ARROW_RIGHT = u'\ue014' # alias
DOWN = u'\ue015'
ARROW_DOWN = u'\ue015' # alias
INSERT = u'\ue016'
DELETE = u'\ue017'
SEMICOLON = u'\ue018'
EQUALS = u'\ue019'
NUMPAD0 = u'\ue01a' # numbe pad keys
NUMPAD1 = u'\ue01b'
NUMPAD2 = u'\ue01c'
NUMPAD3 = u'\ue01d'
NUMPAD4 = u'\ue01e'
NUMPAD5 = u'\ue01f'
NUMPAD6 = u'\ue020'
NUMPAD7 = u'\ue021'
NUMPAD8 = u'\ue022'
NUMPAD9 = u'\ue023'
MULTIPLY = u'\ue024'
ADD = u'\ue025'
SEPARATOR = u'\ue026'
SUBTRACT = u'\ue027'
DECIMAL = u'\ue028'
DIVIDE = u'\ue029'
F1 = u'\ue031' # function keys
F2 = u'\ue032'
F3 = u'\ue033'
F4 = u'\ue034'
F5 = u'\ue035'
F6 = u'\ue036'
F7 = u'\ue037'
F8 = u'\ue038'
F9 = u'\ue039'
F10 = u'\ue03a'
F11 = u'\ue03b'
F12 = u'\ue03c'
META = u'\ue03d'
COMMAND = u'\ue03d'
|
class Account:
""" A simple account class """
""" The constructor that initializes the objects fields """
def __init__(self, owner, amount=0.00):
self.owner = owner
self.amount = amount
self.transactions = []
def __repr__(self):
return f'Account {self.owner},{self.amount} '
def __str__(self):
return f'Account belongs to {self.owner} and has a balance of {self.amount} Ksh Only '
""" Create new Accounts"""
acc1 = Account('Victor') # Amount is initialized with a default value of 0.0
acc2 = Account('Roseline', 1000.00) # Amount is initialized with the value 1000.00
print('')
print(str(acc2))
print(repr(acc1))
|
def my_cleaner(dryrun):
if dryrun:
print('dryrun, dont really execute')
return
print('execute cleaner...')
def task_sample():
return {
"actions" : None,
"clean" : [my_cleaner],
}
|
def NumFunc(myList1=[],myList2=[],*args):
list3 = list(set(myList1).intersection(myList2))
return list3
myList1 = [1,2,3,4,5,6]
myList2 = [3, 5, 7, 9]
NumFunc(myList1,myList2)
|
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/7/19 下午7:00
# @Author : Latent
# @Email : [email protected]
# @File : sequence_num.py
# @Software: PyCharm
# @class : 对于库存的清洗
"""
字段说明:
1.inventory_id ---->数据库自增
2.num ---> 当前库存
3.num_level ---> 库存等级
"""
class Sequence_Num(object):
# 1. 库存等级换算 ------> 库存0-50->紧张 50-100 -> 正常 100以上充足
@classmethod
def sequence_num_level(cls, data):
platform = data['platform']
if platform != 'pdd':
_func_none = (lambda x: x if type(x) == int else 0)
item_num = int(_func_none(data['public']['num']))
if item_num <= 50:
num_level = '紧张'
elif 50 < item_num <= 100:
num_level = '正常'
else:
num_level = '充足'
else:
item_num = int(data['public']['num'])
if item_num <= 300:
num_level = '紧张'
elif 300 < item_num <= 999:
num_level = '正常'
else:
num_level = '充足'
num_info = {'num': item_num,
'num_level': num_level}
return num_info
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
ans = list()
for node in lists:
val = node
while (val != None):
ans.append(val.val)
val = val.next
ans = sorted(ans)
sub = None
point = None
for x in ans:
if sub == None:
sub = ListNode(x)
point = sub
else:
point.next = ListNode(x)
point = point.next
return sub
# home = None
# point = None
# val = None
# while True:
# val = None
# for i in range(len(lists)):
# if lists[i] == None:
# continue
# if val == None:
# val = i
# continue
# if lists[i].val < lists[val].val:
# val = i
# if val == None:
# break
# if home == None:
# home = lists[val]
# point = home
# lists[val] = lists[val].next
# else:
# point.next = lists[val]
# point = point.next
# lists[val] = lists[val].next
# return home
|
"""
1-Recolectar los tipos del AST en diccionario
2-Recolectar Métodos de tipos
3-Verificar la semántica
"""
class battle_sim_typing:
def __init__(self, program, collector, builder, definer,checker, context):
self.program=program
self.collector=collector
self.builder=builder
self.definer=definer
self.checker=checker
self.context=context
def __call__(self):
self.context.create_type("Type",acces=False)
self.context.create_type("number",acces=False)
self.context.create_type("bool",acces=False)
self.context.create_type("None",acces=False)
self.context.define_func("print", "void", ["x"], ["Type"])
t=self.context.create_type("List",acces=False)[1]
t.define_func("append", "void", ["x"], ["Type"])
t.define_func("remove", "void", ["x"], ["Type"])
self.context.create_type("LandMap",args=["no_rows", "no_columns", "passable_map", "height_map", "sea_height"],type_args=["number","number","List","List","number"])
t=self.context.create_type("BSObject",args=["id","life_points","defense"],type_args=["number","number","number"],acces=False)[1]
t.define_var("id", "number")
t.define_var("life_points", "number")
t.define_var("defense","number")
t.define_func("take_damage","void",["damage"],["number"])
t.define_func("put_in_cell", "void", ["map","row","col"], ["LandMap","number","number"])
t=self.context.create_type("Cell", args=["passable","row" , "column", "height"],type_args=["number","number","number","number"],acces=False)[1]
t.define_var("row","number")
t.define_var("col", "number")
t.define_var("passable", "number")
t.define_var("height", "number")
t.define_var("bs_object", "BSObject")
self.context.create_type("StaticObject", args=["id","life_points","defense"], type_args=["number","number","number"],parent="BSObject",acces=False)
t=self.context.create_type("BSUnit",args=["id","life_points","defense","attack","moral","ofensive","min_range","max_range","radio","vision","intelligence","recharge_turns","solidarity","movil"],type_args=["number","number","number","number","number","number","number","number","number","number","number","number","bool","bool"], parent="BSObject",acces=False)[1]
t.define_var("attack","number")
t.define_var("moral", "number")
t.define_var("ofensive", "number")
t.define_var("min_range", "number")
t.define_var("max_range", "number")
t.define_var("radio", "number")
t.define_var("vision", "number")
t.define_var("intelligence", "number")
t.define_var("recharge_turns", "number")
t.define_var("recharging_turns", "number")
t.define_var("solidarity","bool")
t.define_var("movil", "bool")
t.define_func("calculate_distance","number",["cell1","cell2"],["Cell","Cell"])
t.define_func("nearby_friend","bool",["cell"],["Cell"])
t.define_func("enemy_in_range","List",["cell"],["Cell"])
t.define_func("in_range_of_enemy","number",["cell"],["Cell"])
t.define_func("move_cost_calculate","number",["cell"],["Cell"])
t.define_func("enemy_cost_calculate","number",["enemy"],["BSUnit"])
t.define_func("friend_in_danger","bool",["cell"],["Cell"])
t.define_func("enemy_to_attack","BSUnit",[],[])
t.define_func("take_damage","void",["damage"],["number"])
t.define_func("attack_enemy","void",["enemy"],["BSUnit"])
t.define_func("move_to_cell","void",["cell"],["Cell"])
t.define_func("turn","void",[],[])
self.context.create_type("LandUnit", args=["id","life_points","defense","attack","moral","ofensive","min_range","max_range","radio","vision","intelligence","recharge_turns","solidarity","movil"],type_args=["number","number","number","number","number","number","number","number","number","number","number","number","bool","bool"],parent="BSUnit",acces=False)[1]
self.context.create_type("NavalUnit", args=["id","life_points","defense","attack","moral","ofensive","min_range","max_range","radio","vision","intelligence","recharge_turns","solidarity","movil"],type_args=["number","number","number","number","number","number","number","number","number","number","number","number","bool","bool"], parent="BSUnit", acces=False)[1]
t=self.context.create_type("Side", ["id", "units"], ["number", "List"])[1]
t.define_var("id", "number")
t.define_var("units", "List")
t.define_var("no_own_units_defeated", "number")
t.define_var("no_enemy_units_defeated", "number")
t.define_func("add_unit", "void", ["unit"], ["BSUnit"])
t.define_func("remove_unit", "void", ["unit"], ["BSUnit"])
t=self.context.create_type("Simulator",["map","Sides","turns", "interval"],["LandMap","List","number","number"])[1]
t.define_func("start", "void", [], [])
self.context.define_func("build_random_map", "LandMap", ["percent","rows","cols"], ["number","number","number"])
self.collecting()
self.building()
self.define_context()
self.checking()
def collecting(self):
self.collector.visit(self.program)
def building(self):
self.builder.visit(self.program)
def define_context(self):
self.definer.visit(self.program)
def checking(self):
self.checker.visit(self.program)
|
for i in range(10):
print('Привет', i)
# [перегрузка функции range()]
# Напишем программу, которая выводит те числа
# из промежутка [100;999], которые оканчиваются на 7.
for i in range(100, 1000): # перебираем числа от 100 до 999
if i % 10 == 7: # используем остаток от деления на 10, для получения последней цифры
print(i)
# 3 параметра
for i in range(56, 171, 2):
print(i)
# Отрицательный шаг генерации
for i in range(5, 0, -1):
print(i, end=' ')
print('Взлетаем!!!')
|
'''Faça um programa que tenha uma função chamada escreva(), que recebe um texto qualquer
como parâmetro e mostre uma mensagem com o tamanho adaptável'''
def escreva(msg):
tam = len(msg)+4
print('~'*tam)
print(f' {msg}')
print('~'*tam)
#Programa principal
escreva('Gustavo Guanabara')
escreva('oi')
escreva('Curso em video de Python')
|
# Copyright (C) 2021 <FacuFalcone - CaidevOficial>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def bag(sizeBag: int, kilos: list, values: list, index: int):
# Base Case 1
if index == 0 or sizeBag == 0:
return 0
# Base Case 2
elif kilos[index-1] > sizeBag:
return bag(sizeBag, kilos, values, index-1)
return max(values[index-1]+bag(sizeBag-kilos[index-1], kilos, values, index-1), bag(sizeBag, kilos, values, index-1))
if __name__ == "__main__":
values = [60, 100, 120]
kilos = [10, 20, 30]
sizeBag = 50
index = len(values)
result = bag(sizeBag, kilos, values, index)
print(result)
|
"""
lab9
"""
#3.1
class my_stat():
def cal_sigma(self,m,n):
self.result=0
for i in range (n,m+1):
self.result=self.result+i
return self.result
def cal_p(self,m,n):
self.result=1
for i in range (n,m+1):
self.result=self.result*i
return self.result
def cal_f(self,m):
if m == 0:
return(1)
else:
return m * self.cal_f(m-1)
def cal_pr(self,m,n):
return(self.cal_f(m)/self.cal_f(m-n))
#3.3
my_cal = my_stat()
print(my_cal.cal_sigma(5,3))
my_cal = my_stat()
print(my_cal.cal_p(5,3))
print(my_cal.cal_f(5))
print (my_cal.cal_pr(5,3))
|
#Replace all ______ with rjust, ljust or center.
THICKNESS = int(input()) #This must be an odd number
c = 'H'
# Top Cone
for i in range(THICKNESS):
print((c*i).rjust(THICKNESS-1)+c+(c*i).ljust(THICKNESS-1))
# Top Pillars
for i in range(THICKNESS+1):
print((c*THICKNESS).center(THICKNESS*2)+(c*THICKNESS).center(THICKNESS*6))
# Middle Belt
for i in range((THICKNESS+1)//2):
print((c*THICKNESS*5).center(THICKNESS*6))
# Bottom Pillars
for i in range(THICKNESS+1):
print((c*THICKNESS).center(THICKNESS*2)+(c*THICKNESS).center(THICKNESS*6))
# Bottom Cone
for i in range(THICKNESS):
print(((c*(THICKNESS-i-1)).rjust(THICKNESS)+c+(c*(THICKNESS-i-1)).ljust(THICKNESS)).rjust(THICKNESS*6))
|
cellsize = 200
cells = {}
recording = False
class Cell:
def __init__(self, x, y, ix, iy):
self.x, self.y = x, y
self.ix, self.iy = ix, iy # positional indices
self.xdiv = 1.0
self.ydiv = 1.0
self.left = None
self.up = None
def left_inter(self):
if self.left:
return self.f(frameCount)[0] + self.left.left_inter()
else:
return self.f(frameCount)[0]
def up_inter(self):
if self.up:
return self.f(frameCount)[1] + self.up.up_inter()
else:
return self.f(frameCount)[1]
def f(self, fc):
return cos(fc/self.xdiv), sin(fc/self.ydiv)
def draw_me(self):
pushStyle()
pushMatrix()
translate(self.x, self.y)
fill(0, 0, 1)
noStroke()
circle(0, 0, 5)
# calculate interference from previous cells
# average out based on position
ix = self.left_inter() / self.ix
iy = self.up_inter() / self.iy
fill(0, 1, 1, 0.5)
circle(ix*cellsize*0.3, iy*cellsize*0.3, 2)
popMatrix()
popStyle()
def __repr__(self):
return "{}, {}".format(self.x, self.y)
def setup():
size(800, 800)
colorMode(HSB, 360, 1, 1, 1)
background(0, 0, 0)
for x in range(4):
for y in range(4):
cells[x,y] = Cell(x*cellsize+cellsize/2, y*cellsize+cellsize/2, x+1, y+1)
cells[x,y].xdiv, cells[x,y].ydiv = 100.0, 100.0
# set up neighbour properties
for y in range(4):
for x in range(4):
if x != 0:
cells[x,y].left = cells[x-1,y]
if y != 0:
cells[x,y].up = cells[x,y-1]
cells[0,0].xdiv, cells[0,0].ydiv = 100.0, 100.0
# set up vertical seeds
for i in range(1,4):
cells[0,i].xdiv, cells[0,i].ydiv = random(50, 100), random(30, 50)
# set up horizontal seeds
for i in range(1,4):
cells[i,0].xdiv, cells[i,0].ydiv = random(30, 50), random(50, 100)
def draw():
noStroke()
fill(0, 0, 0, 0.04)
square(0, 0, height)
for k in cells:
cells[k].draw_me()
if recording and frameCount < 1500:
saveFrame("frames/#####.png")
else:
noLoop()
print("Done.")
|
jogadores = list()
jogador = dict()
desempenho = list()
resp = 'S'
while resp not in 'N':
print('-=' * 20)
jogador['nome'] = str(input('Nome do jogador: '))
quant = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
soma = 0
for partida in range(0, quant):
gol = int(input(f'{jogador["nome"]} fez quantos gols na partida {partida+1}? '))
soma += gol
desempenho.append(gol)
jogador['gols'] = desempenho[:]
jogador['total'] = soma
jogadores.append(jogador.copy())
desempenho.clear()
while True:
resp = str(input('Quer continuar? [S/N] '))[0].upper()
if resp in 'SN':
break
print('ERRO! Responda apenas S ou N.')
if resp == 'N':
break
print('-=-' * 16)
print('cod', end=' ')
for k in jogadores[0].keys():
print(f'{k:<20}', end=' ')
print('\n', '-' * 48)
for i, v in enumerate(jogadores):
print(f'{i:3}', end=' ')
for dado in v.values():
print(f'{str(dado):<20}', end=' ') # Foi usado o str() pra não dar erro na formatação
print()
while True:
print('-=' * 32)
qual = int(input('Mostrar dados de qual jogador? (999 p/ parar) '))
if qual == 999:
break
if qual > len(jogadores)-1 or qual < 0:
print(f'ERRO! Não existe jogador com código {qual}! Tente novamente')
else:
print(f'Levantamento do jogador {jogadores[qual]["nome"]}')
for i, gol in enumerate(jogadores[qual]['gols']):
print(f'No jogo {i+1} fez {gol} gols')
print()
print('Volte Sempre!')
|
HUOBI_URL_PRO = "https://api.huobi.sg"
HUOBI_URL_VN = "https://api.huobi.sg"
HUOBI_URL_SO = "https://api.huobi.sg"
HUOBI_WEBSOCKET_URI_PRO = "wss://api.huobi.sg"
HUOBI_WEBSOCKET_URI_VN = "wss://api.huobi.sg"
HUOBI_WEBSOCKET_URI_SO = "wss://api.huobi.sg"
class WebSocketDefine:
Uri = HUOBI_WEBSOCKET_URI_PRO
class RestApiDefine:
Url = HUOBI_URL_PRO
class HttpMethod:
GET = "GET"
GET_SIGN = "GET_SIGN"
POST = "POST"
POST_SIGN = "POST_SIGN"
class ApiVersion:
VERSION_V1 = "v1"
VERSION_V2 = "v2"
def get_default_server_url(user_configed_url):
if user_configed_url and len(user_configed_url):
return user_configed_url
else:
return RestApiDefine.Url
|
"""
Tests using cards CLI (command line interface).
"""
def test_add(db_empty, cards_cli, cards_cli_list_items):
# GIVEN an empty database
# WHEN a new card is added
cards_cli("add something -o okken")
# THEN The listing returns just the new card
items = cards_cli_list_items("list")
assert len(items) == 1
assert items[0].summary == "something"
assert items[0].owner == "okken"
def test_list_filter(db_empty, cards_cli, cards_cli_list_items):
"""
Also kinda tests update
"""
# GIVEN
# two items owned by okken, one that is done
# two items with no owner, one that is done
cards_cli("add -o okken one")
cards_cli("add -o anyone two")
cards_cli("add -o okken three")
cards_cli("add four")
cards_cli("add five")
# get the ids for a couple of them
items = cards_cli_list_items("list")
for i in items:
if i.summary in ("three", "four"):
cards_cli(f"update {i.id} -d")
# `cards --noowner -o okken -d` should return two items
items = cards_cli_list_items("list --noowner -o okken -d")
assert len(items) == 2
for i in items:
assert i.summary in ("three", "four")
assert i.done == "x"
assert i.owner in ("okken", "")
def test_count(db_empty, cards_cli):
cards_cli("add one")
cards_cli("add two")
assert cards_cli("count") == "2"
def test_delete(db_empty, cards_cli, cards_cli_list_items):
# GIVEN a db with 2 items
cards_cli("add one")
cards_cli("add two")
an_id = cards_cli_list_items("list")[0].id
# WHEN we delete one item
cards_cli(f"delete {an_id}")
# THEN the other card remains
assert cards_cli("count") == "1"
def test_version(cards_cli):
"""
Should return 3 digits separated by a dot
"""
version = cards_cli("version").split(".")
assert len(version) == 3
assert all([d.isdigit() for d in version])
|
class NeuroLangException(Exception):
"""Base class for NeuroLang Exceptions"""
pass
class UnexpectedExpressionError(NeuroLangException):
pass
class NeuroLangNotImplementedError(NeuroLangException):
pass
class ForbiddenExpressionError(NeuroLangException):
"""
Generic exception specifying an error in the program.
"""
pass
class ForbiddenDisjunctionError(ForbiddenExpressionError):
"""
Probabilistic queries do not support disjunctions.
A probabilistic choice can be added for a predicate symbol by using the
`add_probabilistic_choice_from_tuples` method of a probabilistic Neurolang
engine. But you cannot add multiple probabilistic facts or rule for the
same
predicate.
Examples
----------
ProbActivation(r, PROB(r)) :- RegionReported(r, s) & SelectedStudy(s)
ProbActivation(r, PROB(r)) :- ~RegionReported(r, s) & SelectedStudy(s)
This example program adds a disjunction of probabilistic queries which is
not allowed.
"""
pass
class ForbiddenExistentialError(ForbiddenExpressionError):
pass
class RelationalAlgebraError(NeuroLangException):
"""
Base class for Relational Algebra provenance exceptions.
"""
pass
class NotConjunctiveExpression(NeuroLangException):
"""
This expression is not conjunctive. In this case, an expression is
conjunctive if it is a conjunction of
- Constant
- A function or predicate of constants
"""
pass
class NotConjunctiveExpressionNegation(NotConjunctiveExpression):
"""
This expression is not conjunctive. In this case, an expression is
conjunctive if it is a conjunction of
- Constant
- A function or predicate of conjunctive arguments
- A negated predicate of conjunctive arguments
"""
pass
class NotConjunctiveExpressionNestedPredicates(NotConjunctiveExpression):
"""
This expression is not conjunctive. In this case, an expression is
conjunctive if it is a conjunction of
- Constant
- A function or predicate of conjunctive arguments
- A quantifier of conjunctive arguments
Note that in this case, negated predicates are not valid (negation and
aggregation cannot be used in the same rule).
Examples
--------
StudyMatchingRegionSegregationQuery(count(s), r) :-
RegionReported(r, s) & ~RegionReported(r2, s)
& RegionLabel(r2) & (r2 != r)
The above expression is not conjunctive since it uses an aggregate
function `count` in combination with a negated predicate
`~RegionReported`.
"""
pass
class ProjectionOverMissingColumnsError(RelationalAlgebraError):
"""
One of the predicates in the program has wrong arguments.
See `WrongArgumentsInPredicateError`
"""
pass
class RelationalAlgebraNotImplementedError(
RelationalAlgebraError, NotImplementedError
):
"""
Neurolang was unable to match one of the relational algebra operations
defined in the program. This is probably due to a malformed query.
"""
pass
class ForbiddenBuiltinError(ForbiddenExpressionError):
pass
class NotInFONegE(ForbiddenExpressionError):
pass
class NeuroLangFrontendException(NeuroLangException):
pass
class SymbolNotFoundError(NeuroLangException):
"""
A symbol is being used in a rule without having been previously
defined.
"""
pass
class RuleNotFoundError(NeuroLangException):
pass
class UnsupportedProgramError(NeuroLangException):
"""
Some parts of the datalog program are (currently) unsupported.
"""
pass
class UnsupportedQueryError(NeuroLangException):
"""
Queries on probabilistic predicates are unsupported.
"""
pass
class UnsupportedSolverError(NeuroLangException):
pass
class ProtectedKeywordError(NeuroLangException):
"""
One of the predicates in the program uses a reserved keyword.
Reserved keywords include : {PROB, with, exists}
"""
pass
class ForbiddenRecursivityError(UnsupportedProgramError):
"""
The given program cannot be stratified due to recursivity.
When using probabilistic queries, a query can
be solved through stratification if the probabilistic and deterministic
parts are well separated. In case there exists one within-language
probabilistic query dependency, no probabilistic predicate should appear
in the stratum that depends on the query.
The same holds for aggregate or negated queries. If a rule contains an
aggregate or negated term, all the predicates in the body of the rule
must be computed in a previous stratum.
Examples
--------
B(x) :- A(x), C(x)
A(x) :- B(x)
This program cannot be stratified because it contains a loop in
the dependencies of each rule. Rule `B(x) :- A(x), C(x)` depends
on the second rule through its occurence of the predicate `A(x)`.
But rule `A(x) :- B(x)` in turn depends on the first rule through
the `B(x)` predicate.
"""
pass
class ForbiddenUnstratifiedAggregation(UnsupportedProgramError):
"""
The given Datalog program is not valid for aggregation. Support for
aggregation is done according to section 2.4.1 of [1]_.
A program is valid for aggregation if it can be stratified into
strata P1, . . . , Pn such that, if A :- ...,B,... is a rule in P such
that A contains an aggregate term, and A is in stratum Pi while B is in
stratum Pj, **then i > j**.
In other terms, all the predicates in the body of a rule containing an
aggregate function must be computed in a previous stratum. Recursion
through aggregation is therefore not allowed in the same stratum.
Examples
--------
The following datalog program is invalid for stratified aggregation
p(X) :- q(X).
p(sum<X>) :- p(X).
.. [1] T. J. Green, S. S. Huang, B. T. Loo, W. Zhou,
Datalog and Recursive Query Processing.
FNT in Databases. 5, 105–195 (2012).
"""
pass
class WrongArgumentsInPredicateError(NeuroLangException):
"""
One of the predicates in the query has the wrong number of arguments.
Examples
--------
NetworkReported is defined with two variables but used with three
in the second rule:
NetworkReported(n, s) :- RegionReported(
r, s
) & RegionInNetwork(r, n)
StudyMatchingNetworkQuery(s, n) :- (
RegionReported("VWFA", s)
& NetworkReported(n, s, r)
)
"""
pass
class TranslateToNamedRAException(NeuroLangException):
"""
Base exception for errors translating Datalog to Named Relational Algebra.
"""
pass
class NoValidChaseClassForStratumException(NeuroLangException):
"""
Neurolang implements stratified datalog which splits a datalog program
into several independent strata that can each be solved by a specific
chase algorithm based on the properties of the rules in the stratum
(using negation, aggregation and/or recursion).
This exception is raised if there is no valid algorithm available to
solve a specific stratum; e.g. no recursive compatible algorithm was
provided to solve a recursive stratum.
See `neurolang.datalog.chase.__init__.py` for available chase
implementations.
"""
pass
class CouldNotTranslateConjunctionException(TranslateToNamedRAException):
"""
This conjunctive formula could not be translated into an equivalent
relational algebra representation. This is probably because the
formula is not in *modified relational algebra normal form*.
Generaly speaking, the formula must be expressed in *conjunctive normal
form* (CNF) or *disjunctive normal form* (DNF): as either a conjunction of
disjunctions or disjunction of conjunctions.
See 5.4.7 from [1]_.
Examples
--------
PositiveReverseInferenceSegregationQuery(
t, n, PROB(t, n)
) :- (TopicAssociation(t, s) // SelectedStudy(s)) // (
StudyMatchingNetworkQuery(s, n) & SelectedStudy(s)
)
This formula is not in DNF since it is a disjunction of a disjunction
(TopicAssociation(t, s) // SelectedStudy(s)) and a conjunction
(StudyMatchingNetworkQuery(s, n) & SelectedStudy(s)).
A valid query would be :
PositiveReverseInferenceSegregationQuery(
t, n, PROB(t, n)
) :- (TopicAssociation(t, s) & SelectedStudy(s)) // (
StudyMatchingNetworkQuery(s, n) & SelectedStudy(s)
)
.. [1] S. Abiteboul, R. Hull, V. Vianu, Foundations of databases
(Addison Wesley, 1995), Addison-Wesley.
"""
def __init__(self, output):
super().__init__(f"Could not translate conjunction: {output}")
self.output = output
class NegativeFormulaNotSafeRangeException(TranslateToNamedRAException):
"""
This rule is not *range restricted* and cannot be solved in
*nonrecursive datalog with negation*. One of the variables in this rule
appears in a negated literal without also appearing in a non-negated
literal.
A datalog rule composed of literals of the form R(v) or ¬R(v) is
*range restricted* if each variable x occurring in the rule occurs in at
least one literal of the form R(v) (non-negated literal) in the rule body.
See 5.2 from [1]_.
Examples
--------
StudyNotMatchingSegregationQuery(s, n) :- (
~StudyMatchingNetworkQuery(s, n)
& Network(n)
)
Variable `s` is present in the negated `StudyMatchingNetworkQuery`
literal but is not present in a non-negated literal. A valid query body
would be :
StudyNotMatchingSegregationQuery(s, n) :- (
~StudyMatchingNetworkQuery(s, n)
& Study(s) & Network(n)
)
.. [1] S. Abiteboul, R. Hull, V. Vianu, Foundations of databases
(Addison Wesley, 1995), Addison-Wesley.
"""
def __init__(self, formula):
super().__init__(f"Negative predicate {formula} is not safe range")
self.formula = formula
class NegativeFormulaNotNamedRelationException(TranslateToNamedRAException):
"""
This rule contains a negative literal R(v) which was not previously
defined as a non-negated relation.
Examples
--------
t(x, y) :- r(x, y) & q(y, z)
s(x, y, prob(x, y)) :- ~t(x, x) & q(x, y)
"""
def __init__(self, formula):
super().__init__(f"Negative formula {formula} is not a named relation")
self.formula = formula
class NonLiftableException(NeuroLangException):
pass
|
def index(array,index):
try:
return array[index]
except:
return array
def append(array,value):
try:
array.append(value)
except:
pass
return array
def remove(array,index):
try:
del array[index]
except:
pass
return array
def dedupe(array):
try:
return list(dict.fromkeys(array))
except:
return array
|
class Entity():
def __init__(self, entityID, type, attributeMap):
self.__entityID = entityID
self.__type = type
self.__attributeMap = attributeMap
@property
def entityID(self):
return self.__entityID
@entityID.setter
def entityID(self, entityID):
self.__entityID = entityID
@property
def type(self):
return self.__type
@type.setter
def type(self, type):
self.__type = type
@property
def attributeMap(self):
return self.__attributeMap
@attributeMap.setter
def attributeMap(self, attributeMap):
self.__attributeMap = attributeMap
|
""" Abstract Syntax Tree Nodes """
class AST: ...
class LetraNode(AST):
def __init__(self, token):
self.token = token
def __repr__(self):
return f'{self.token}'
class NumeroNode(AST):
def __init__(self, token):
self.token = token
def __repr__(self):
return f'{self.token}'
class BinOpNode(AST):
def __init__(self, left, token, right):
self.left = left
self.token = token
self.right = right
def __repr__(self):
return f'{self.left} : {self.token} : {self.right}'
class UnaryOpNode(AST):
def __init__(self, op_tok, node):
self.op_tok = op_tok
self.node = node
def __repr__(self):
return f'{self.op_tok}, {self.node}'
class BaryabolAccessNode(AST):
def __init__(self, baryabol_name):
self.baryabol_name = baryabol_name
def __repr__(self):
return f'{self.baryabol_name}'
class BaryabolAssignNode(AST):
def __init__(self, baryabol_name, expression):
self.baryabol_name = baryabol_name
self.expression = expression
def __repr__(self):
return f'{self.baryabol_name} : {self.expression}'
class IpahayagNode(AST):
def __init__(self, ipapahayag):
self.ipapahayag = ipapahayag
def __repr__(self):
return f'{self.ipapahayag}'
class KungNode(AST):
def __init__(self, expressions, condition, body):
self.expressions = expressions
self.condition = condition
self.body = body
def __repr__(self):
return f'{self.condition}'
class TukuyinEstablishNode(AST):
def __init__(self, func_name, params, body):
self.func_name = func_name
self.params = params
self.body = body
def __repr__(self):
return f'{self.condition}'
class TukuyinAccessNode(AST):
def __init__(self, func_name, params):
self.func_name = func_name
self.params = params
def __repr__(self):
return f'{self.condition}'
|
def funcao_numero(num = 0):
ultimo = num
primeiro = 1
while True:
for c in range(1,primeiro + 1):
print(f'{c} ',end=' ')
print()
primeiro += 1
if primeiro > ultimo:
break
num = int(input('Informe um número para ver uma tabela personaliada: '))
funcao_numero(num)
|
#
# from src/3dgraph.c
#
# a part of main to tdGraph
#
_MAX_VALUE = float("inf")
class parametersTDGraph:
def __init__(self, m, n, t, u, minX, minY, minZ, maxX, maxY, maxZ):
self.m = m
self.n = n
self.t = t
self.u = u
self.minX = minX
self.minY = minY
self.minZ = minZ
self.maxX = maxX
self.maxY = maxY
self.maxZ = maxZ
def tdGraph(plotter, aFunction, parameters):
P = parameters
lowerHorizon = [ _MAX_VALUE for _ in range(P.m + 4 * P.n + 1) ]
upperHorizon = [ -_MAX_VALUE for _ in range(P.m + 4 * P.n + 1) ]
for i in range(P.n + 1):
flagA = False
z = P.minZ + (P.maxZ - P.minZ) / P.n * i
for j in range(P.m + 1):
flagB = False
idx = j + 2 * (P.n - i)
x = P.minX + (P.maxX - P.minX) / P.m * j
y = P.t * (aFunction(x, z) - P.minY) / (P.maxY - P.minY) + P.u * i
if y < lowerHorizon[idx]:
lowerHorizon[idx], flagB = y, True
if y > upperHorizon[idx]:
upperHorizon[idx], flagB = y, True
if flagB and flagA:
plotter.draw(2 * idx, 2 * y)
else:
plotter.move(2 * idx, 2 * y)
flagA = flagB
|
# -*- coding: utf-8 -*-
"""
fahrToCelsius is the function that converts the input temperature from degrees Fahrenheit
to degrees Celsius.
tempFahrenheit is input value of temperature in degrees Fahrenheit.
convertedTemp is returned value of the function that is value of temperature in degrees Celsius.
tempClassifier is the function that classifies temperature into 4 different classes (0,1,2,3).
tempCelsius is input value of temperature in degrees Celsius.
The fuction returns value of class (0 - cold, 1 - slippery, 2 - comfortable, 3 - warm)
Author: Pavel Zhuchkov - 21.03.2018
Modified by - None
"""
# Definition of the function that converts Fahrenheit to Celsius
def fahrToCelsius(tempFahrenheit):
convertedTemp = (tempFahrenheit - 32) / 1.8
return convertedTemp
# Definition of the function that classifies temperature into 4 different classes
def tempClassifier(tempCelsius):
if tempCelsius < -2:
return 0
elif tempCelsius >= -2 and tempCelsius <= 2:
return 1
elif tempCelsius > 2 and tempCelsius <= 15:
return 2
else:
return 3
|
class CreateSingleEventRequest:
def __init__(self, chart_key, event_key=None, table_booking_config=None, social_distancing_ruleset_key=None):
if chart_key:
self.chartKey = chart_key
if event_key:
self.eventKey = event_key
if table_booking_config is not None:
self.tableBookingConfig = table_booking_config.to_json()
if social_distancing_ruleset_key is not None:
self.socialDistancingRulesetKey = social_distancing_ruleset_key
|
#
# PySNMP MIB module PYSNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PYSNMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:43:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Bits, NotificationType, enterprises, IpAddress, Counter64, MibIdentifier, ObjectIdentity, ModuleIdentity, Counter32, iso, TimeTicks, Unsigned32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Bits", "NotificationType", "enterprises", "IpAddress", "Counter64", "MibIdentifier", "ObjectIdentity", "ModuleIdentity", "Counter32", "iso", "TimeTicks", "Unsigned32", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408))
pysnmp.setRevisions(('2017-04-14 00:00', '2005-05-14 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: pysnmp.setRevisionsDescriptions(('Updated addresses', 'Initial revision',))
if mibBuilder.loadTexts: pysnmp.setLastUpdated('201704140000Z')
if mibBuilder.loadTexts: pysnmp.setOrganization('The PySNMP Project')
if mibBuilder.loadTexts: pysnmp.setContactInfo('E-mail: Ilya Etingof <[email protected]> GitHub: https://github.com/etingof/pysnmp')
if mibBuilder.loadTexts: pysnmp.setDescription('PySNMP top-level MIB tree infrastructure')
pysnmpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 1))
pysnmpExamples = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 2))
pysnmpEnumerations = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3))
pysnmpModuleIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1))
pysnmpAgentOIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 2))
pysnmpDomains = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 3))
pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999))
pysnmpNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4))
pysnmpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 0))
pysnmpNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 1))
pysnmpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5))
pysnmpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 1))
pysnmpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 2))
mibBuilder.exportSymbols("PYSNMP-MIB", pysnmpNotifications=pysnmpNotifications, pysnmpObjects=pysnmpObjects, pysnmpGroups=pysnmpGroups, pysnmp=pysnmp, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpExamples=pysnmpExamples, pysnmpCompliances=pysnmpCompliances, PYSNMP_MODULE_ID=pysnmp, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpConformance=pysnmpConformance, pysnmpExperimental=pysnmpExperimental, pysnmpDomains=pysnmpDomains)
|
def uniform_cost_search(graph, start, goal):
path = []
explored_nodes = list()
if start == goal:
return path, explored_nodes
path.append(start)
path_cost = 0
frontier = [(path_cost, path)]
while len(frontier) > 0:
path_cost_till_now, path_till_now = pop_frontier(frontier)
current_node = path_till_now[-1]
explored_nodes.append(current_node)
if current_node == goal:
return path_till_now, explored_nodes
neighbours = graph[current_node]
neighbours_list_int = [int(n) for n in neighbours]
neighbours_list_int.sort(reverse=False)
neighbours_list_str = [str(n) for n in neighbours_list_int]
for neighbour in neighbours_list_str:
path_to_neighbour = path_till_now.copy()
path_to_neighbour.append(neighbour)
extra_cost = 1
neighbour_cost = extra_cost + path_cost_till_now
new_element = (neighbour_cost, path_to_neighbour)
is_there, indexx, neighbour_old_cost, _ = get_frontier_params_new(neighbour, frontier)
if (neighbour not in explored_nodes) and not is_there:
frontier.append(new_element)
elif is_there:
if neighbour_old_cost > neighbour_cost:
frontier.pop(indexx)
frontier.append(new_element)
return None, None
|
def fibonacci(n):
seznam = []
(a, b) = (0, 1)
for i in range(n):
(a, b) = (b, a+b)
seznam.append(a)
return [a, seznam]
def stevke(stevilo):
n = 1
while n > 0: #nevem kako naj bolje napisem
if fibonacci(n)[0] > 10 ** (stevilo -1):
return fibonacci(n)[1].index(fibonacci(n)[0]) + 1
n = n + 1
print(stevke(1000))
|
spam = 42 # global variable
def printSpam():
print('Spam = ' + str(spam))
def eggs():
spam = 42 # local variable
return spam
print('example xyz')
def Spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
def assignSpam(var):
global spam
spam = var
Spam()
printSpam()
assignSpam(25)
printSpam()
|
"""
URL: https://codeforces.com/problemset/problem/1422/C
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: combinatorics, dp, math, *1700
---------------------In Progress---------------------
"""
mod = 10 ** 9 + 7
def a(s):
# s = input()
ll = len(s)
summ = 0
for i in range(ll):
current_digit = int(s[i])
c1 = current_digit * 10 ** (ll - i - 1) * i * (i + 1) // 2
c2_coff = ''.join([str(j) for j in range(ll - i - 1, 0, -1)])
if len(c2_coff) > 9:
c2_coff = 987654321
elif len(c2_coff) > 0:
c2_coff = int(c2_coff)
else:
c2_coff = 0
c2 = current_digit * c2_coff
summ += c1
summ += c2
summ %= mod
print(summ)
a('100500100500')
a('107')
|
def binarySearch(nums, target):
# 左右都闭合的区间 [l, r]
l, r = 0, len(nums) - 1
while l <= r:
mid = (left + right) >> 1
if nums[mid] == target:
return mid
# 搜索区间变为 [mid+1, right]
if nums[mid] < target:
l = mid + 1
# 搜索区间变为 [left, mid - 1]
if nums[mid] > target:
r = mid - 1
return -1
|
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
print (ar.count(max(ar)))
#https://www.hackerrank.com/challenges/birthday-cake-candles/problem
|
class Project:
def __init__(self, id=None, name=None, description=None):
self.id = id
self.name = name
self.description = description
def __repr__(self):
return "%s: %s, %s" % (self.id, self.name, self.description)
def __eq__(self, other):
return self.id == other.id and self.name == other.name
def __lt__(self, other):
return int(self.id) < int(other.id)
|
class Service:
def __init__(self, name):
self.name = name
self.methods = {}
def rpc(self, func_name):
def decorator(func):
self._save_method(func_name, func)
return func
if isinstance(func_name, str):
return decorator
func = func_name
func_name = func.__name__
return decorator(func)
def _save_method(self, method: str, func):
self.methods[method] = func.__name__
def get_methods(self, obj):
methods = {}
for method, func_name in self.methods.items():
func = getattr(obj, func_name)
methods[method] = func
return methods
|
'''
Дополните приведенный код, используя срезы, так чтобы он вывел строку s в обратном порядке.
'''
s = "In 2010, someone paid 10k Bitcoin for two pizzas."
print(s[::-1])
|
def prime_factors(strs):
result = []
float=2
while float:
if strs%float==0:
strs = strs / float
result.append(float)
else:
float = float+1
if float>strs:
break
return result
|
'''
Steven Kyritsis CS100
2021F Section 031 HW 10,
November 12, 2021
'''
#3
def shareoneletter(wordlist):
d={}
for w in wordlist:
d[w]=[]
for i in wordlist:
match=False
for c in w:
if c in i:
match=True
if match and i not in d[w]:
d[w].append(i)
return d
print(shareoneletter(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))
|
"""
Given a sequence, find the length of its longest repeating subsequence (LRS).
A repeating subsequence will be the one that appears at least twice in the original
sequence and is not overlapping (i.e. none of the corresponding characters in the
repeating subsequences have the same index).
Example 1:
Input: “t o m o r r o w”
Output: 2
Explanation: The longest repeating subsequence is “or” {tomorrow}.
Example 2:
Input: “a a b d b c e c”
Output: 3
Explanation: The longest repeating subsequence is “a b c” {a a b d b c e c}.
"""
# Time: O(N^2) Space: O(N)
def find_LRS_length(str):
n = len(str)
dp = [[0 for _ in range(n+1)] for _ in range(n+1)]
maxLength = 0
# dp[i1][i2] will be storing the LRS up to str[0..i1-1][0..i2-1]
# this also means that subsequences of length zero(first row and column of
# dp[][]), will always have LRS of size zero.
for i1 in range(1, n+1):
for i2 in range(1, n+1):
if i1 != i2 and str[i1 - 1] == str[i2 - 1]:
dp[i1][i2] = 1 + dp[i1 - 1][i2 - 1]
else:
dp[i1][i2] = max(dp[i1 - 1][i2], dp[i1][i2 - 1])
maxLength = max(maxLength, dp[i1][i2])
return maxLength
def main():
print(find_LRS_length("tomorrow"))
print(find_LRS_length("aabdbcec"))
print(find_LRS_length("fmff"))
main()
|
# A server used to store and retrieve arbitrary data.
# This is used by: ./dispatcher.js
def main(request, response):
response.headers.set(b'Access-Control-Allow-Origin', b'*')
response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST')
response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type')
response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate')
if request.method == u'OPTIONS': # CORS preflight
return b''
uuid = request.GET[b'uuid']
stash = request.server.stash;
with stash.lock:
queue = stash.take(uuid)
if queue is None:
queue = []
if request.method == u'POST':
queue.append(request.body)
ret = b'done'
else:
if len(queue) == 0:
ret = b'not ready'
else:
ret = queue.pop(0)
stash.put(uuid, queue)
return ret;
|
clarify_boosted = {
'abita cove': ["cooked cod"],
'the red city': ["baked potatoes", "carrots", "iron ingot"],
'claybound': ["cooked salmon"]
}
aliases = {
'Quartz': 'Quartz Crystal',
'Potatoes': 'Baked Potatoes',
'Nether Wart': 'Nether Wart Block'
}
|
while True:
linha = input("Digite qualquer coisa ou \"fim\" para terminar: ")
if linha == "fim":
break
print(linha)
print("Fim!")
|
"""
What you will learn:
- How to add, subtract, multiply divide numbers
- Float division and integer division
- Modulus (finding the remainder)
- Dealing with exponents
- Python will crash on errors (like divide by 0)
Okay now lets do more cool things with variables. Like making python do math for us!
What you need to do:
Pt 1
- solve x = 45 + 4(4/6+2)^5 --- should = 584.391
- solve x = (4/5*5+1)^.5 --- should = 2.23607
Pt 2
- understand why divide0 and divide1 have different results
- what is mod0 and mod1
- write code to determine if 39879827239498734985798 is divisible by 3 without a remainder
Pt 3
- divide a number by 0. Watch what happens. Note the type of error it is
Pt 4
- try to add an int and string together. What happens?
"""
x = 6
y = 2
adder = x + y # some simple addition
suber = x - y # some simple subtraction
multr = x * y # some simple multiplication
divide0 = x / y
divide1 = x // y
mod0 = x % y
mod1 = y % x
power = x ** 6 # the "**" means to the power of
p0 = "Hi "
P1 = " My Name IS"
P2 = " Slime Shady"
P = p0 + P1 + P2
print(P)
|
phrase = input('Enter a phrase: ')
for c in phrase:
if c in 'aeoiuAEOIU':
print(c)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.