text stringlengths 37 1.41M |
|---|
#dia de la semana por numero
numero = int(input(" ingresen el numero = "))
if numero >= 1 and numero <= 7:
if numero ==1:
print("lunes")
if numero ==2:
print("martes")
if numero ==3:
print("miercoles")
if numero ==4:
print("jueves")
if numero ==5:
print("viern... |
import os
os.system('cls')
#P7E15
#Desarrolla un programa utilizando que nos sirva para gestionar
# nuestros contactos (la información a gestionar
# será el teléfono, nombre, apellido1, apellido2 y correo electrónico. El programa
# tendrá un menú, con las siguientes opciones: añadir contacto, consultar contacto
# a pa... |
import os
os.system('cls')
#P7E8
#Escribe un programa que pida una frase (entrada por teclado),
# y pase la frase como parámetro a una función que debe eliminar
# los espacios en blanco (compactar la frase). El programa principal
# imprimirá por pantalla el resultado final.
frase=input("Introduzca una frase: ")
esp... |
"""
What is a state_dict in PyTorch
===============================
In PyTorch, the learnable parameters (i.e. weights and biases) of a
``torch.nn.Module`` model are contained in the model’s parameters
(accessed with ``model.parameters()``). A ``state_dict`` is simply a
Python dictionary object that maps each layer to ... |
"""
Text classification with the torchtext library
==============================================
In this tutorial, we will show how to use the torchtext library to build the dataset for the text classification analysis. Users will have the flexibility to
- Access to the raw data as an iterator
- Build data pro... |
# -*- coding: utf-8 -*-
"""
Spatial Transformer Networks Tutorial
=====================================
**Author**: `Ghassen HAMROUNI <https://github.com/GHamrouni>`_
.. figure:: /_static/img/stn/FSeq.png
In this tutorial, you will learn how to augment your network using
a visual attention mechanism called spatial tr... |
"""
`Learn the Basics <intro.html>`_ ||
`Quickstart <quickstart_tutorial.html>`_ ||
`Tensors <tensorqs_tutorial.html>`_ ||
`Datasets & DataLoaders <data_tutorial.html>`_ ||
`Transforms <transforms_tutorial.html>`_ ||
`Build Model <buildmodel_tutorial.html>`_ ||
**Autograd** ||
`Optimization <optimization_tutorial.html>... |
"""
Changing default device
=======================
It is common practice to write PyTorch code in a device-agnostic way,
and then switch between CPU and CUDA depending on what hardware is available.
Typically, to do this you might have used if-statements and ``cuda()`` calls
to do this:
.. note::
This recipe requ... |
char_total = 0
result = 0
while True:
try:
string = raw_input()
except EOFError:
print ("Error: EOF or empty input!")
break
char_total += len(string)
backslash = string.count("\\\\")*2
string = string.replace("\\\\", ' ')
result += string.count("\"")*2 + string.count("\... |
def xy(coord):
x = 0
y = 0
for xy in coord:
if xy == '^':
x += 1
elif xy == 'v':
x -= 1
elif xy == '>':
y += 1
elif xy == '<':
y -= 1
coords.add((x,y))
coord_input = list(raw_input())
santa = coord_input[0::2]
robot = c... |
import unittest
# O(n^2). Array slicing
class Solution:
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
if not num:
return False
def is_valid_additive(a, b, c_index):
while True:
c = a + b
... |
import unittest
import heapq
import itertools
def _kth_largest(nums, k):
heap = []
for num in itertools.islice(nums, 0, k):
heapq.heappush(heap, num)
for num in itertools.islice(nums, k, len(nums)):
if num >= heap[0]:
heapq.heappushpop(heap, num)
return heap[0]
def _kth_s... |
import unittest
def partition(nums, lo, hi):
pivot = nums[hi - 1]
w = lo
for r in range(lo, hi):
if nums[r] > pivot:
nums[r], nums[w] = nums[w], nums[r]
w += 1
nums[w], nums[hi - 1] = nums[hi - 1], nums[w]
return w
def kth_largest(nums, lo, hi, k):
pivot_ind... |
import unittest
_offset = ord('0') << 1
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = []
if len(a) < len(b):
a, b = b, a
carry = 0
i = len(a) - 1
for j in range(len(b... |
import unittest
from typing import List, Optional
import utils
from tree import TreeNode
# O(n) time. O(log(n)) space. Recursive DFS.
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def dfs(lo, hi):
if lo >= hi:
return None
mid =... |
import unittest
# O(n)
class Solution:
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
is_one_bit = False
i = 0
while i < len(bits):
is_one_bit = not bits[i]
i += 1 if is_one_bit else 2
return is_... |
import unittest
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sorted(nums)[len(nums) >> 1]
class Test(unittest.TestCase):
def test(self):
self._test([1, 2, 2, 2], 2)
self._test([-1], -1)
def _tes... |
import unittest
from tree import TreeNode
class Solution:
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = []
sum_ = 0
curr = root
while curr or stack:
if curr:
stack.append(curr)
... |
import unittest
class Solution:
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0
class Test(unittest.TestCase):
def test(self):
self._test(1, True)
self._test(2, True)
self._test(3, True)
self._test(4, False)
... |
import unittest
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token == '+':
stack.append(stack.pop() + stack.pop())
elif token == '-':
... |
import unittest
import utils
# O(n) time. O(n) space. Iteration.
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
if len(num1) < len(num2):
num1, num2 = num2, num1
result = []
carry = 0
for i in range(len(num1)):
a = ord(num1[len(num1) -... |
import unittest
from typing import List
import utils
# O(n^2) time. O(1) space. Brute-force.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, a in enumerate(nums):
for j in range(i + 1, len(nums)):
if a + nums[j] == target:
... |
import unittest
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if not nums or len(nums) * len(nums[0]) != r * c:
return nums
width = len(nums[0])... |
import unittest
import utils
def parse_num(s, i):
while i < len(s) and s[i] == ' ':
i += 1
num = 0
while i < len(s) and s[i].isdigit():
num = num * 10 + ord(s[i]) - ord('0')
i += 1
return i, num
def parse_operator(s, i):
while i < len(s) and s[i] == ' ':
i += 1... |
import unittest
import utils
# Built-in string searching.
class Solution:
def rotateString(self, a, b):
"""
:type a: str
:type b: str
:rtype: bool
"""
if len(a) != len(b):
return False
a += a
# See CPython fast search
# https:/... |
import unittest
from typing import List
import utils
# O(n * sum(nums)) time. O(sum(nums)) space. Space-optimized DP, 0-1 knapsack.
class Solution:
def canPartition(self, nums: List[int]) -> bool:
s = sum(nums)
if s & 1:
return False
target = s >> 1
# dp[j]: can you ... |
import unittest
import utils
class ProductOfNumbers:
def __init__(self):
self.products = [1]
def add(self, num: int) -> None:
if num == 0:
self.products = [1]
else:
self.products.append(self.products[-1] * num)
def getProduct(self, k: int) -> int:
... |
import unittest
from tree import TreeNode
class Solution:
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def make_bst_greater_again(node, sum_):
if not node:
return sum_
node.val += make_bst_greater_again(n... |
import unittest
import test_0385
from nested_integer import NestedInteger
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.stack = []
self.next_index = -1
if nestedList:
self.curr_list = nestedList
self.next_item = self._move_next()
... |
import collections
import unittest
from typing import Optional
import utils
from tree import TreeNode
# O(n) time. O(n) space. BFS.
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
q = collections.deque()
q.append(root)
depth ... |
import unittest
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if not x:
return 0
if n < 0:
pos = False
n = -n
else:
pos... |
import unittest
from tree import TreeNode
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
return []
result = []
q = [root]
while q:
sum_ = 0
next_q =... |
import math
import unittest
import utils
def reverse(num):
result = 0
while num > 0:
num, r = divmod(num, 10)
result = result * 10 + r
return result
class Solution:
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
... |
import unittest
import utils
# O(n) time. O(1) space. Iteration.
class Solution:
def shortestToChar(self, s, c):
"""
:type s: str
:type c: str
:rtype: List[int]
"""
distances = [0] * len(s)
hi = s.find(c)
for i in range(hi):
distances[i]... |
import unittest
class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while num > 9:
new_num = 0
while num:
num, r = divmod(num, 10)
new_num += r
num = new_num
return num
cl... |
import unittest
from typing import Optional
import utils
from tree import TreeNode
# O(n) time. O(log(n)) space. Top down, recursive DFS.
class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
result = 0
def dfs(curr, length, is_left):
nonlocal result
r... |
import itertools
import unittest
import utils
# O(n!) time. O(n) space. Backtracking.
class Solution:
def largestTimeFromDigits(self, a):
"""
:type a: List[int]
:rtype: str
"""
result = -1
for p in itertools.permutations(a):
hour = p[0] * 10 + p[1]
... |
import unittest
import math
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
max_power_3 = int(math.pow(3, math.floor(math.log(0x7fffffff, 3))))
return not max_power_3 % n
class Test(unittes... |
import unittest
class Solution:
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo = 0
hi = (len(nums) >> 1) - 1
while lo <= hi:
mid = lo + ((hi - lo) >> 1)
if nums[mid << 1] == nums[(mid << 1) + 1]:
... |
import unittest
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
s = list(s)
# trim whitespaces at start, end and between words
i = 0
target_lo = 0
while True:
while i < n and s[i] =... |
import unittest
class Solution:
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
was_space = True
count = 0
for ch in s:
if ch != ' ':
if was_space:
count += 1
was_space = False
... |
import unittest
class Solution:
def findRelativeRanks(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
for rank, (i, num) in enumerate(sorted(enumerate(nums), reverse=True, key=lambda x: x[1])):
if rank > 2:
nums[i] = str(rank + 1)
... |
import unittest
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
lo = 0
hi = len(height) - 1
lo_height = height[lo]
hi_height = height[hi]
max_area = min(lo_height, hi_height) * (hi - lo)
while l... |
import unittest
class Solution:
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
return s.count('A') < 2 and s.count('LLL') == 0
class Test(unittest.TestCase):
def test(self):
self._test('PPALLP', True)
self._test('PPALLL', False)
def _... |
import unittest
from linkedlist import ListNode
class Solution:
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
sorted_head = ListNode(0)
while head:
val = head.val
... |
import unittest
from typing import List
import math
import utils
# O(n) time. O(1) space. Algebra, arithmetic progression.
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
result = [0] * num_people
repeat = int((math.sqrt(1 + 8 * candies) - 1) / 2)
... |
import unittest
from linkedlist import ListNode
class Solution:
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
t = head
h = head
while True:
h = h.next
if not ... |
import functools
import unittest
from typing import List
import utils
class Solution:
def shortestSuperstring(self, words: List[str]) -> str:
@functools.lru_cache(None)
def suffix(w1, w2):
best = w2
for i in range(len(w1) + 1):
if w2.startswith(w1[-i:]):
... |
import unittest
class Solution:
def lengthLongestPath(self, input):
"""
:type input: str
:rtype: int
"""
max_len = 0
path_lengths = {0: 0}
for seg in input.split('\n'):
name = seg.lstrip('\t')
depth = len(seg) - len(name)
... |
import unittest
from typing import Optional
import utils
from tree import TreeNode
def dfs(node):
a = node.val # robbing this node
b = 0 # not robbing this node
if node.left:
la, lb = dfs(node.left)
a += lb
b += max(la, lb)
if node.right:
ra, rb = dfs(node.right)
... |
import unittest
from typing import List
import utils
# O(n) time. O(n) space. DFS.
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
def dfs(i):
if isConnected[i][i] == 0:
return False
isConnected[i][i] = 0
for j in range(i):... |
import random
import unittest
def binary_search(a, x, lo=0, hi=-1):
n = len(a)
if hi < 0:
hi += n
# See OpenJDK Arrays.binarySearch0():
# https://github.com/openjdk/jdk/blob/f37d9c8abca50b65ed232831a06d60c1d015013f/src/java.base/share/classes/java/util/Arrays.java#L1829
# See CoreCLR Arra... |
import unittest
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
mask = num
mask |= mask >> 1
mask |= mask >> 2
mask |= mask >> 4
mask |= mask >> 8
mask |= mask >> 16
return num ^ mask
class ... |
import unittest
import collections
max_balls = 6
def _delete_3balls(board, lo, hi):
if lo < 0:
return board[:lo + 1] + board[hi:]
while True:
ball = board[lo]
new_lo, new_hi = lo - 1, hi
while new_lo >= 0 and board[new_lo] == ball:
new_lo -= 1
while new_hi ... |
import unittest
from typing import List
import utils
# O(n) time. O(1) space. Kadane's algorithm.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_so_far = max_ending_here = 0
for i in range(1, len(prices)):
diff = prices[i] - prices[i - 1]
max_ending_he... |
import unittest
from tree import TreeNode, null
class Solution:
def __init__(self):
self.sum = 0
self.paths = []
def pathSum(self, root, sum_):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return ... |
import unittest
import collections
def _read_element(formula, i):
i += 1
while i < len(formula) and formula[i].islower():
i += 1
return i
def _read_num(formula, i):
num = ord(formula[i]) - ord('0')
i += 1
while i < len(formula) and formula[i].isdigit():
num = num * 10 + ord(f... |
import unittest
import utils
def evaluate_xyz(x, y, z, p, q):
yz = evaluate_yz(y, z, q)
return x + yz if p == '+' else x - yz
def evaluate_yz(y, z, q):
return y * z if q == '*' else y // z
def dfs(s, i):
# Any expression given by this problem can be reduced to an equivalent general form: x + y * ... |
import unittest
from linkedlist import ListNode
class Solution:
def getIntersectionNode(self, a, b):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
def list_len(x):
result = 0
while x:
x = x.next
result += 1
... |
import unittest
class Solution:
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
if n < 10:
return n
n -= 10
num_digits = 2
count = 90
while n >= count * num_digits:
n -= count * num_digits
num... |
import unittest
import math
class Solution:
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
w = int(math.sqrt(area))
while area % w:
w -= 1
return [area // w, w]
class Test(unittest.TestCase):
def test(self):
... |
import unittest
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lo = 0
hi = len(nums) - 1
while lo <= hi:
mid = lo + ((hi - lo) >> 1)
mid_val = nums[mid]
... |
import unittest
class Solution:
def convert(self, s, n):
"""
:type s: str
:type n: int
:rtype: str
"""
if n == 1 or n >= len(s):
return s
result = [''] * n
row = 0
step = 1
for ch in s:
result[row] += ch
... |
import collections
import unittest
from typing import List
import utils
from tree import TreeNode
# O(n) time. O(number of groups) space. Hash table.
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
group_size_to_people = collections.defaultdict(list)
for perso... |
import unittest
from typing import List
import utils
# O(n) time. O(n) space. Kadane's algorithm, DP.
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# dp[i]: the maximum subarray that ends at i
dp = [0] * len(nums)
dp[0] = max_so_far = nums[0]
for i in range(1, le... |
import unittest
from tree import TreeNode, null
class Solution:
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
stack = [root]
prev = TreeNode(0)
while stack:
curr = stack... |
import unittest
from typing import List
import utils
# O(len(coins) * amount) time. O(amount) space. Space-optimized DP, unbounded knapsack.
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
max_num_coins = amount + 1
# dp[j]: the fewest number of coins you need in coin... |
import unittest
def gcd_euclid(a, b):
if a == 0 or b == 0:
return 0
while b != 0:
a, b = b, a % b
return a
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place inste... |
import unittest
from linkedlist import ListNode
class Solution:
def deleteDuplicates(self, head):
"""
:type curr: ListNode
:rtype: ListNode
"""
curr = head
while curr:
next_ = curr.next
while next_ and next_.val == curr.val:
n... |
import unittest
# O(n).
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return -1
hi_sum = sum(nums)
lo_sum = 0
for i, num in enumerate(nums):
hi_sum -= num
if lo... |
import unittest
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
if aStr == '':
return 0
else:
return lenRecur(aStr[:-1]) + 1
class TestLenRecur(unittest.TestCase):
def test_with_len_one(self):
self.assertEqual(lenRecur('a'), 1)
def... |
# Практика. Класс Point
from math import sqrt
class Point:
list_points = []
# Метод написания кода DRY (Don't Repeat Yourself)
def __init__(self, coord_x = 0, coord_y = 0):
self.x = coord_x
self.y = coord_y
Point.list_points.append(self) # Отразится на всех экземпляра... |
import hashlib, sqlite3, string
def addUser(user, password):
if (special(user)):
return "invlaid character in username"
if (len(password)<8):
return "password too short"
db=sqlite3.connect('data/tables.db')
c=db.cursor()
myHashObj=hashlib.sha1()
myHashObj.update(password)
q... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
===========================================
FileName: list.py
Desc:
Author: ruizhong.li
Version:
CreateTime: 2017-05-01
==========================================
"""
movices = ["The Holy Grail",1975,"Terry Jones & Terry Gilliam",91,["Grah... |
def train_test_split(X, y, train_size=0.8,):
"""
学習用データを分割する。
Parameters
----------
X : 次の形のndarray, shape (n_samples, n_features)
学習データ
y : 次の形のndarray, shape (n_samples, )
正解値
train_size : float (0<train_size<1)
何割をtrainとするか指定
Returns
----------
X_train : 次の... |
#with open('data/product.txt', 'r') as f:
#f_contents = f.read()
#print(f_contents)
#with open('data/product.txt', 'r') as f:
#f_contents = f.readlines()
#print(f_contents, end='')
#with open('data/product.txt', 'r') as f:
#for line in f:
#print(line, end='')
with open... |
x = "Anthony"
y = str.maketrans('nol','xyz')
x = x.translate(y)
print (x)
z = str.maketrans('xyz','nol')
x = x.translate(z)
print (x)
#x[7] = "y"
#x = x[7].replace('o','y')
#print (x)
b = list(x)
b[7] = "y"
print (b)
x = ''.join(b)
print (x)
|
'''
Computational Models of Cognition
Final Project
11/14/18
Functions for implementing and running the Pi-First model in a replication study
of Lee et al. (2011).
'''
import random
import numpy as np
class Game:
def __init__(self, num_arms, pi, gamma, environment):
self.trial = 0
self.arms ... |
""" --- Stonehenge Game ---
=== CSC148 Winter 2018 ===
University of Toronto
Assignment 2
Submitted by: Eric Koehli
=== Module Description ===
This module contains the Stonehenge game and Stonehenge game state.
"""
from typing import Any, List, Union, Dict, Tuple
from copy import deepcopy
from game import Game
from g... |
""" Searching & Sorting Algorithms
=== University of Toronto ===
Department of Computer Science
__author__ = 'Eric K'
=== Module Description ===
This module contains some searching and sorting algorithms.
"""
from typing import List, Tuple
# Remark: recall that len([1, 2, 3]) == 3 and
# len(lst) - 1 is the last ind... |
import sympy as sp
from sympy.logic.boolalg import Or, And
_op_identity = {And: True, Or: False}
def check_value(order):
""" Checks that the value of order is between 0 and 1 """
if not (0 <= order <= 1):
raise ValueError
def unique(sequence):
""" Returns the sequence without duplicate elements... |
def myAbs(n):
if n > 0:
return n
else:
return -n
print(myAbs(10))
# x作为定参,n可缺省默认2
def power(x, n=2):
c = 1;
while n > 0:
n -= 1
c = c * x
return c
print(power(2, 10))
def count(x):
sum = 0
for n in x:
sum += n;
return sum
print('count=', ... |
"""
graph2analysis.py does the graph analysis for graph2 (built by graph2.py).
We compare the diameter of graph2 with the diameter of 20 random graphs.
The random graphs are erdos-renyi graphs where p=edge density of graph2
If a graph is not connected, we calculate the diameter by summing the
diameters of each con... |
# Reading train and building the decision tree
train_df = pd.read_csv('sample_train.csv')
train_df = train_df.drop(columns=['reviews.text'])
print('Building Tree...')
root = build_tree(train_df)
print('Tree was built successfully')
print()
# Evaluating the accuracy by traversing the tree using the train sample... |
def type_finder(l):
return [str(item) for item in l if (type(item) == int or type(item) == float)]
# new_list = []
# for item in l:
# if type(item) == int:
# new_list.append(str(item))
# return new_list
list_items = [1,2,3,4,(1,2,3,4,),{1:3,3:5,},'rohit','mohit',1.1,2.5]... |
name = input("Enter your name :")
print(f"The reverse of entred name is {name[::-1]}") |
# num1 = input("Enter 1 numbers " )
# num2 = input("Enter 2 numbers " )
# num3 = input("Enter 3 numbers " )
# num1,num2,num3 = int(input("Enter three numbers " )).split()
# average = (num1 + num2 + num3)/3
# print("Average of values are " + str(average))
# print(f"The average of {num1},{num2} and {num3} are {aver... |
def cube_function(numbers):
new = {}
for i in range(1,numbers+1):
new[i] = i**3
return new
num = 5
print(cube_function(num)) |
menu = {'noodle':'500원', 'ham':'200원', 'egg':'100원', 'spaghetti':'900원'}
# Dictionary로 선언된 메뉴에서 메뉴의 이름(key)만을 추출해 리스트로 생성 및 해당 리스트를 메뉴목록으로 출력하기 위한 String 작업 수행
menuList = list(menu.keys())
menuStr = '('
i = 0
for i in range(len(menuList)):
menuStr += menuList[i] + ' '
i += 1
menuStr += ')'
while 1:
print('안... |
import collections
class LRUCache:
def __init__(self, limit=10):
self.limit = limit
self.cache = collections.OrderedDict()
"""
Retrieves the value associated with the given key. Also needs to move the key-value pair to the top of the order such that the pair is considered most-recently used... |
from logical.player import Player
import random
class Game:
def __init__(self, name, tiles, score, amount):
self.player_name = name
self.player_tiles = tiles
self.player_score = score
self.players_amount = amount
#EL JUEGO ACABA CUANDO EL JUGADOR SE QUEDA SIN TURNOS, TRADUCE A MAN... |
'''
Created on Jan 23, 2015
@author: Kwadwo Yeboah
A first principle implementation of a Priority Queue
'''
from math import floor
class PriorityQueue():
def __init__(self):
self.__myHeap = []
def add(self, obj):
self.__myHeap.append(obj)
... |
class Line:
"""docstring for line"""
def __init__(self,date,split_line_list):
super(Line, self).__init__()
self.line = " "
self.date = date
self.time = split_line_list[0]
self.name = split_line_list[1]
self.content = split_line_list[2]
self.split_line_list = split_line_list
self.word_list = []
def ... |
def SumNum(p, q):
if p == 0:
return q
return SumNum(int(input()), q + p)
p = int(input())
q = 0
print(SumNum(p, q))
|
a, b, c, d, e = int(input()), int(input()), int(input()), \
int(input()), int(input())
if b <= d and c <= e or c <= d and b <= e:
print('YES')
elif a <= d and c <= e or c <= d and a <= e:
print('YES')
elif b <= d and a <= e or a <= d and b <= e:
print('YES')
else:
print('NO')
|
#!/usr/bin/python3
# -*- coding: iso-8859-2 -*
print("Szukamy liczby sposobw, na jakie mona pokry plansz 4x4 identycznymi klockami 2x1.")
# Recursive function to find number of ways to fill a n x 4 matrix
# with 1 x 4 tiles
def totalWays(n):
# base cases
if n < 1:
return 0
if n < 2:
return 1
... |
#!/usr/bin/python3
# -*- coding: iso-8859-2 -*
class Node:
"""Klasa reprezentujca wze drzewa binarnego."""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
... |
#!/usr/bin/python3
# -*- coding: iso-8859-2 -*
def binarne_rek(L, left, right, y):
"""Wyszukiwanie binarne w wersji rekurencyjnej."""
while left < right:
dive = int((left + right) / 2)
if y > L[dive]:
return binarne_rek(L, dive + 1, right, y)
elif y < L[dive]:... |
#!/usr/bin/python3
"""
A function that queries the Reddit API and returns the number of subscribers
"""
from requests import get
def number_of_subscribers(subreddit):
""" Return the number of suscribers """
headers = {'user-agent': 'my-app/0.0.1'}
url = 'https://www.reddit.com/r/{}/about.json'.format(su... |
from collections import Counter as c
import re
alphabet = 'абвгдежзийклмнопрстуфхцчшщъыьэюя'
file1 = open("var3.txt", "r", encoding='utf-8')
var3 = file1.read()
var3 = var3.lower()
var3 = re.sub("[^А-аЯ-я]", "", var3)
#punctuations = [".", ",", "!", "?", ";", ":", "-", "1", "2", "3", "4","5", "6", "7","8","9", "0","—",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.