text stringlengths 37 1.41M |
|---|
# Implement a basic calculator to evaluate a simple expression string.
#
# The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
#
# You may assume that the given expression is always valid.
#
# Some examples:
# "3+2*2" = 7
#... |
# Implement the following operations of a queue using stacks.
#
# push(x) -- Push element x to the back of queue.
# pop() -- Removes the element from in front of queue.
# peek() -- Get the front element.
# empty() -- Return whether the queue is empty.
# Notes:
# You must use only standard operations of a stack -- which... |
# There are a total of n courses you have to take, labeled from 0 to n - 1.
#
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
#
# Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish ... |
"""
Check if a given linked list has a cycle. Return true if it does, otherwise return false.
Assumption:
You can assume there is no duplicate value appear in the linked list.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
... |
"""
Given an array of integers, sort the elements in the array in ascending order. The selection sort algorithm should be used to solve this problem.
Examples
{1} is sorted to {1}
{1, 2, 3} is sorted to {1, 2, 3}
{3, 2, 1} is sorted to {1, 2, 3}
{4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}
Corner Cases
What if the... |
longest = ''
current = ''
for x in s:
if (current == ''):
current = x
elif (current[-1] <= x):
current += x
elif (current[-1] > x):
if (len(longest) < len(current)):
longest = current
current = x
else:
current = x
if (len(current) > len(lon... |
def biggest(listToMeasure):
current_biggest = 0
current_answer = None
for element in listToMeasure:
if element > current_biggest:
current_biggest = element
current_answer = element
return current_answer
def largest_odd_times(X):
""" Assumes X is a non-empty list of i... |
"""
represents a packet and its header values. This class is used as an abstraction of the physical
structure of a packet
"""
class Message:
# attributes:
# sequenceNumber: stored as number
# acknowledgmentNumber: stored as number
# checksumValue: When a message is received, the checksum header is parsed int... |
'''
This creates a csv file with row 1: Title, rows 2 - 22: Genres, row 23: ImdB Score
'''
import csv
genres = ["Action","Adventure","Fantasy","Sci-Fi","Thriller","Documentary","Romance","Animation","Comedy","Family","Musical","Mystery","Western","Drama","History","Sport","Crime","Horror","War","Biography","Music"]
w... |
s=[]
n=int(input("enter the elements:"))
fir i in range(1,n+1):
b=int(input("enter the elements:"))
s=append(b)a.sort()
print("largest elements is :",s[n-1])
|
num=int(input("enter a number:"))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+= digit**3
temp//=10
if num== sum:
print(num,"is an armstrong number")
else:
print(num,"is not an armstrong number")
|
char=input("enter a character:)
if(char=='A' or char=='a' or char=='E' or char=='e' or char=='I' or char=='i' or char=='O' char=='o' or char=='U' or char=='u'):
print(char."is a vowel")
else:
print(char."is a consonant")
|
class MoneyBox:
def __init__(self, capacity):
self.capacity = capacity
self.coins = 0
def can_add(self, v):
if self.coins + v <= self.capacity:
return True
else:
return False
def add(self, v):
if self.can_add(v):
self.co... |
class Produto:
def __init__(self, nome, preco):
self.nome = nome
self.preco = preco
class Produtos:
def __init__(self):
self.produtos = []
def addProduto(self, Produto):
self.produtos.append(Produto)
def listarProdutos(self):
print('Produtos:')
for prod... |
## 1. The GIL ##
import threading
import time
import statistics
def read_data():
with open("Emails.csv") as f:
data = f.read()
times = []
for i in range(100):
start = time.time()
read_data()
end = time.time()
times.append(end - start)
threaded_times = []
for i in range(100):
s... |
''' Changing global variables : Chaning Game Options
>>> screen.inch([row,col] ) 'return a character at row,col'
'''
import curses, time, random
#screen.nodelay(0)
#screen.clear()
#curses.noecho()
#curses.curs_set(0)
def menu():
from shift import shift
screen = curses.initscr()
screen.keypad(1)
dims =... |
# 8.9 Creating a New Kind of Class or Instance Attribute
# Descriptor for a type-checked attribute
class Typed(object):
def __init__(self,name,expected_type):
self.name = name
self.expected_type = expected_type
def __get__(self,instance,cls):
if instance is None: return self
ret... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
016_layers.py
pygame sprites with different layers and parallax scrolling
url: http://thepythongamebook.com/en:part2:pygame:step016
author: horst.jens@spielend-programmieren.at
licence: gpl, see http://www.gnu.org/licenses/gpl.html
change the sprite layer by clicking ... |
import pygame, sys
from pygame.locals import *
# initialize all imported pygame modules
pygame.init()
# pygame.display.set_mode(resolution=(0,0),flags=0, depth=0)
# initialize window
surface = pygame.display.set_mode((400,300))
# set title
pygame.display.set_caption('Hello World')
# run game loop
while True:
for e... |
# 20.8 Adding a Method to a Class Instance at Runtime
def add_method_to_objects_class(obj, method, name=None):
if name is None:
name = method.func_name
class NewClass(obj.__class__):
pass
setattr(NewClass, name, method)
obj.__class__ = NewClass
import inspect
def _rich_str(self):
p... |
class Box:
def __init__(self,*arg):
print arg, type(arg)
print arg[0]
print len(arg)
if type(arg[0]) == tuple:
print 'tuple arg:',arg
self.x,self.y = arg[0]
else:
print 'arg:',arg
self.x, self.y = arg
def __repr__(self):
... |
def A(func):
def wrapper1(*args):
print 'A=>{}{}'.format(func,str(args) )
val = func(*args)
return val
return wrapper1
def B(func): # func = <function wrapper1>
def wrapper2(*args):
print 'B=>{}{}'.format(func,str(args) )
val = func(*args)
return val
retu... |
''' 004 alphademo.py
colorkey and alpha-value
'''
import pygame,os
white = pygame.Color('white')
# image.set_alpha(alpha)
# if you have a pygame surface WITHOUT IN-BUILTIN TRANSPARENCY such as an .JPG image
# you can set an alpha-value(transparency) for the whole surface with set_alpha
def get_alpha_surface(surf,alph... |
"""
Example using OpenPyXL to create an Excel worksheet
"""
from openpyxl import Workbook
import random
# Create an Excel workbook
wb = Workbook()
# Grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
ws['A1'] = "This is a test"
# Rows can also be appended
for i in range(200):
... |
# 016 layers.py
# pygame sprites with different layers and parallax scrolling
# change the sprite layer by clicking with left or right mouse button
# the birdsprites will apear before or behind the blocks
# POINT ON a sprite and press 'p' to print out more information about that sprite
from constants016 import *
clas... |
"""Given a string, find the length of the longest substring in it with no more than K distinct characters.
You can assume that K is less than or equal to the length of the given string.
Example 1:
Input: String="araaci", K=2
Output: 4
Explanation: The longest substring with no more than '2' distinct characters is "a... |
import random;
def memoryQuickSort(arr):
n = len(arr)
if(n <= 1):
return arr
pivotInd = random.randint(0,n-1)
pivot = arr[pivotInd]
l = 0
r = n - 1
newArray = [0] * n
pivotTimes = 0
for i in range(n):
if(arr[i] < pivot):
newArray[l] = arr[i]
... |
import random
def mergeSort(arr):
if(len(arr) == 1):
return arr
arr1 = mergeSort(arr[:len(arr)//2])
arr2 = mergeSort(arr[len(arr)//2:])
ind1 = 0
ind2 = 0
newArray = []
for i in range(len(arr)):
if(ind2 >= len(arr2) or (ind1 < len(arr1) and arr1[ind1] < arr2[ind2])):
... |
def gaussian_kernel(size, sigma=1):
'''
Calculates and Returns Gaussian kernel.
Parameters:
size (int): size of kernel.
sigma(float): standard deviation of gaussian kernel
Returns:
gaussian: A 2d array shows gaussian kernel
'''
#Writer your code here
gaussian = None... |
def classify_leaf(image):
'''
Classifies the input image to only two classes of leaves.
Parameters:
image (numpy.ndarray): The input image.
Returns:
int: The class of the image. 1 == apple, 0 == linden
'''
leaf_type = 0
#Write your code here
img_gray =... |
# Copyright (C) 2020 Logan Bier. All rights reserved.
# project details
# a time-bound distributed currency
# that replaces chain exponential energy usage
# with a finite energy distributed ledger
# made up of a randomly generated set of values
# in a range of natural numbers
# conceptually, energy is conserved by aw... |
def is_divisable(number):
if number%20!=0:
return False
elif number%19!=0:
return False
elif number%18!=0:
return False
elif number%17!=0:
return False
elif number%16!=0:
return False
elif number%15!=0:
return False
elif number%14!=0:
return False
elif number%13!=0:
... |
import math
print('==== Seno, Cosseno e Tangente ====')
angulo = math.radians(int(input('Digte o valor de um ângulo qualquer: ')))
print(f'Para o ângulo de {math.degrees(angulo):.1f}°, o seno é {math.sin(angulo):.2f}, cosseno {math.cos(angulo):.2f} e a tangente {math.tan(angulo):.2f}.')
|
print('\033[32;1m=== Analisando nome ===\033[m')
nome = str(input('\033[31mDigite o seu nome completo: ')).strip()
print(f'\033[36mO seu nome com letras maiúsculas: \033[34;1m{nome.upper()}\033[m')
print(f'\033[36mO seu nome com letras minúsculas: \033[34;1m{nome.lower()}\033[m')
print(f'\033[36mTotal de letras: \033[3... |
print('\033[32;1m==== Conversão de metros em centimetros e milimetros ====\033[m')
m = float(input('\033[34mDigite o valor em metros: '))
cent = m*100
mili = m*1000
print(f'\033[35m{m} metros em centimetros é \033[36m{cent}cm')
print(f'\033[35m{m} metros em milimetros é \033[36m{mili}mm') |
print('\033[32;1m=== Aumento de Salário ===\033[m')
Sal = float(input('\033[31mQual o seu salário? '))
if Sal >= 1250.00:
Sal = Sal + Sal * (10 / 100)
print(f'\033[36mO seu novo salário é de \033[34;1m{Sal}\033[m')
else:
Sal = Sal + Sal * (15 / 100)
print(f'\033[36mO seu novo salário é de \033[34;1m{Sal... |
from random import randint
print('\033[32;1m=== Jogo da adivinhação ===\033[m')
n = int(input('\033[31mAdivinhe o número entre 0 e 5 que eu estou pensando: '))
r = randint(0,5)
if n == r:
print('\033[36mSortudo, você acertou o número que eu estava pensando, PARABÉNS!')
else:
print(f'\033[36mSinto muito, você er... |
print('\033[32;1m==== Conversor de Temperatura ====\033[m')
C = float(input('\033[31mInforme a temperatura em °C: '))
F = C * 1.8 + 32
print(f'\033[36mA conversão de {C:.1f}°C para Fahrenheit é \033[34;1m{F:.1f}°F')
|
print('\033[32;1m==== Antecessor e Sucessor de um número ====\033[m')
n = float(input('\033[31mDigite um número: \033[m'))
print(f'\033[35mO antecessor de \033[34;1m{n}\033[35m é \033[34;1m{n-1}\033[35m e o sucessor é \033[34;1m{n+1}') |
# We are given an array containing ‘n’ objects. Each object, when created, was assigned a unique number from 1 to ‘n’ based on their creation sequence. This means that the object with sequence number ‘3’ was created just before the object with sequence number ‘4’.
# Write a function to sort the objects in-place on the... |
# Minimum Window Sort (medium) #
# Given an array, find the length of the smallest subarray in it which when sorted will sort the whole array.
# Example 1:
# Input: [1, 2, 5, 3, 7, 10, 9, 12]
# Output: 5
# Explanation: We need to sort only the subarray [5, 3, 7, 10, 9] to make the whole array sorted
# Example 2:
# I... |
# Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target.
# Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target.
# Example 1:
# Input: [1, 2, 3, 4, 6], target=6
# Output: [1, 3]
# Explanation: ... |
# LIFO Stack DS using Python Lists (Arrays)
class StacksArray:
def __init__(self):
self.stackArray = []
def __len__(self):
return len(self.stackArray)
def isempty(self):
return len(self.stackArray) == 0
def display(self):
print(self.stackArray)
def top(self):... |
# Given ‘M’ sorted arrays, find the K’th smallest number among all the arrays.
# Example 1:
# Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4], K=5
# Output: 4
# Explanation: The 5th smallest number among all the arrays is 4, this can be verified from the merged
# list of all the arrays: [1, 2, 3, 3, 4, 6, 6, 7, 8]
#... |
# Given an array of points in the a 2D2D plane, find ‘K’ closest points to the origin.
# Example 1:
# Input: points = [[1,2],[1,3]], K = 1
# Output: [[1,2]]
# Explanation: The Euclidean distance between (1, 2) and the origin is sqrt(5).
# The Euclidean distance between (1, 3) and the origin is sqrt(10).
# Since sqrt(... |
# Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array.
# The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists of three different numbe... |
# Given a list of intervals representing the start and end time of ‘N’ meetings, find the minimum number of rooms required to hold all the meetings.
# Example 1:
# Meetings: [[1,4], [2,5], [7,9]]
# Output: 2
# Explanation: Since [1,4] and [2,5] overlap, we need two rooms to hold these two meetings. [7,9] can
# occur... |
# We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array has some duplicates, find all the duplicate numbers without using any extra space.
# Example 1:
# Input: [3, 4, 4, 5, 5]
# Output: [4, 5]
# Example 2:
# Input: [5, 4, 7, 2, 3, 5, 3]
# Output: [3, 5]
def swap(i, j, arra... |
# FIFO Queue with Lists/ Array
class Queues:
def __init__(self):
self.QueueList = []
def __len__(self):
return len(self.QueueList)
def isempty(self):
return len(self.QueueList) == 0
def display(self):
print(self.QueueList)
def enqueue(self, element):
s... |
# Given an array of ‘K’ sorted LinkedLists, merge them into one sorted list.
# Example 1:
# Input: L1=[2, 6, 8], L2=[3, 6, 7], L3=[1, 3, 4]
# Output: [1, 2, 3, 3, 4, 6, 6, 7, 8]
# Example 2:
# Input: L1=[5, 8, 9], L2=[1, 7]
# Output: [1, 5, 7, 8, 9]
from heapq import *
class ListNode:
def __init__(self, value... |
# Design a class to calculate the median of a number stream. The class should have the following two methods:
# insertNum(int num): stores the number in the class
# findMedian(): returns the median of all numbers inserted in the class
# If the count of numbers inserted in the class is even, the median will be the aver... |
# Problem Statement #
# Given a string, find if its letters can be rearranged in
# such a way that no two same characters come next to each other.
# Example 1:
# Input: "aappp"
# Output: "papap"
# Explanation: In "papap", none of the repeating characters come next to each other.
# Example 2:
# Input: "Programming"
... |
# Given the head of a LinkedList and two positions ‘p’ and ‘q’, reverse the LinkedList from position ‘p’ to ‘q’.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(te... |
# 计算0到这个元素的所有的平方和
import time
def cpu_bound(number):
print(sum(i ** 2 for i in range(0, number)))
def calc_sums(numbers):
for number in numbers:
cpu_bound(number)
def main():
start_time = time.perf_counter()
numbers = [10000000 + x for x in range(20)]
calc_sums(numbers)
end_time = time... |
'''
Created on Sep 20, 2018
@author: jgonzales
'''
# -*- coding:utf-8 -*-
print(sum([x*x for x in range(1,10+1) if x*x % 2 == 0])) |
a = int(input("Ingrese un numero: "))
b = int(input("Ingrese otro numero: "))
resultado = a + b
print("El resultado es:",resultado)
|
'''
Created on Sep 20, 2018
@author: jgonzales
'''
# -*- coding:utf-8 -*-
numeros = list(range(1,10+1))
for n in numeros:
if n % 2 == 0:
print(n)
print(sum([x*x for x in numeros if x*x % 2 == 0]))
|
#
i = 0
#this is a while loop kinda like a if statment
#so it runs this code until the statment is false
# so it coubnts from 1 to 10
while i <= 10:
print(i)
i = i + 1
# or you can do i += 1 does the same thing
print("done with loop")
|
#
print(" ")
print("Welcome to this translator")
print("this transltor will translate from english to my plop language")
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "W"
else:
translatio... |
# this is a function you have to have def
# say_hi is the name of the function you have to have the this():
# you also have to indent the the thing that is in the function
def say_hi():
print("hello user")
#this is just showing the flow of the code
print("Top")
#this is going to excute the function or some people sa... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import dblquad
from scipy.integrate import tplquad
def trapz(func,start,end,Num_steps):
"""
Trapz takes an equation (func), start and end points, and the number of trapezoids you want to use.
Trapz... |
#This should be a programm that will be able to encrypt
#and decrypt data stored in Caesar Cipher
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',... |
a = input().upper()
s = input().upper()
b = s.split()
if a in b:
k = b.count(a)
print(k, end=" ")
if s.startswith(a):
print(0)
elif s.endswith(a) and k==1:
print(s.index(" "+a)+1)
else:
print(s.index(" "+a+" ")+1)
else:
print(-1) |
nums = [1,2,3,4,5,20,30,40,50]
def count_pairs_sum_target(nums, target):
n = len(nums)
nums.sort()
l,r = 0,n-1
cnt = 0
while l < r:
if nums[l] + nums[r] > target:
cnt += r - l
r -= 1
else:
l += 1
return cnt
|
def isPrime(n):
if n < 2: return False
if n == 2: return True
if not n & 1: return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
N = int(input())
# for i in range(1,N+1):
# if isPrime(i):
# print(i,end=" ")
primes = filter(isPr... |
from functools import lru_cache
# @lru_cache(None)
# def canMakeSubsequence(str1, str2):
# if not str2:
# return True
# if not str1:
# return False
# a,b = ord(str1[0]), ord(str2[0])
# if a==b or a+1==b or a-b==25:
# return canMakeSubsequence(str1[1:],str2[1:])
# else:
# ... |
# list argument must be sorted in ascending order.
import bisect
a = [2, 4, 6, 8, 10, 12, 14]
x = 7
i = bisect.bisect_left(a,x)
print(i)
a.insert(i, x)
print(a)
b = [2, 4, 6, 8, 8, 8, 10, 12, 14]
x = 8
i = bisect.bisect_left(b,x)
print(i)
a = [1, 3, 5, 6, 7, 9, 10, 12, 14]
x = 8
i = bisect.bisect_left(a, x, lo=2, hi=... |
maze = [[0, 0, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
row = col = 6
def countPath(i,j,count):
if i==row-1 and j==col-1:
count += 1
else:
maze[i][j]=2
if j<col-1 and maze[i][... |
import heapq
from collections import Counter
# inputText = "this is an example for huffman encoding"
# frequencyCounter = Counter(inputText)
text = "aaabbcccdddd"
frequencyCounter = Counter(text)
print(frequencyCounter)
def huffman_encode(frequencyCounter):
heap = [[freq, [sym, ""]] for sym,freq in frequencyCoun... |
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def preorder(root): # 先序,先root
if not root:
return []
result = [root.data]
result.extend(preorder(root.left))
result.extend(preorder(root.right))
... |
def count_integer_pairs(a, b, c):
dp = [[0] * (c+1) for _ in range(c+1)]
dp[0][0] = 1
for x in range(c+1):
for y in range(c+1):
if a*x + b*y <= c:
dp[x][y] = 1
for x in range(1, c+1):
for y in range(c+1):
if y > 0:
dp[x][y] += dp[... |
def compute_transition_table(pattern, alphabet):
pattern_len = len(pattern)
transition_table = [0] * (pattern_len + 1)
transition_table[0] = -1
for i in range(pattern_len):
transition_table[i + 1] = transition_table[i] + 1
while transition_table[i + 1] > 0 and pattern[i] != pattern[tran... |
from collections import defaultdict
a = input()
b = input()
a = list(pattern)
b = str.split(" ")
if len(a)!=len(b):
return False
l = len(a)
d1, d2 = defaultdict(list),defaultdict(list)
for i in range(l):
if (a[i] not d1 and b[i] not in d2) or (a[i] in d1 and b[i] in d2 and d1[a[i]] == d2[b[i]]):
d1[a[... |
# At the core of Sorted Containers is the mutable sequence data type SortedList.
# The SortedList maintains its values in ascending sort order.
# As with built-in list datatype, SortedList supports duplicate elements and fast random-access indexing.
from sortedcontainers import SortedList
sl = SortedList()
# Values may... |
def find_number_pairs(arr, target):
n = len(arr)
left = 0
right = n - 1
pairs = []
while left < right:
if arr[left] + arr[right] > target:
# 找到一个数字对
pairs.append((arr[left], arr[right]))
# 继续寻找下一个可能的数字对
right -= 1
else:
# 数... |
T = int(input())
for i in range(T):
C = list(map(int, input().split(" ")))[1]
total = sum(list(map(int,input().split(" "))))
if total > C:
print("No")
else:
print("Yes")
|
#namedtuples
#deque
#ChainMap
#Counter
#OrderedDict
#defaultdict
# dq[1]=z is OK, when dq[1:2] error.
# The major advantage of deques over lists is that inserting
# items at the beginning of a deque is much faster than inserting
# items at the beginning of a list, although inserting items at the
# end of a deque is v... |
import bisect
def maximumJumps(nums, target):
n = len(nums)
jump = [(0,0)] # (跳的次数,下标)
for i in range(1,n):
for p in jump[::-1]:
if abs(nums[p[1]]-nums[i]) <= target:
# jump.insort((p[0]+1, i))
bisect.insort(jump, (p[0]+1, i))
break
... |
# Given an array, check whether the array is in sorted order with recursion
def is_array_sorted(A):
if len(A)==1:
return True
return A[0]<=A[1] and is_array_sorted(A[1:])
A = [127, 220, 246, 277, 321, 454, 534, 565, 933]
print(is_array_sorted(A)) |
# 连续子数组和的绝对值的最大值
# 状态转移方程: f[i] = max(f[i-1]+nums[i], nums[i]) = max(f[i-1],0)+nums[i]
def maxabssum(nums):
ans = f_max = f_min = 0
for x in nums:
f_max = max(f_max, 0) + x
f_min = min(f_min, 0) + x
ans = max(ans, f_max, -f_min)
return ans
nums = [1,-3,2,3,-4]
print(maxabssum(nums... |
grid = [[0, 0, 0, 0, 0, 1],
[1, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[0, 1, 1, 0, 0, 1],
[0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 2]]
def search(x,y):
if grid[x][y] == 2:
print('found at',x,y)
return True
elif grid[x][y] == 1:
print('Wall at',x,y)
... |
#由于python3浮点数的四舍五入不精确,自己写四舍五入精确一位小数的方法
def myround(x):
y = x*10
if y - int(y) < 0.5:
res = int(y)
else:
res = int(y)+1
return res/10
# N = int(input())
# if N<=150:
# res = 0.4463 * N
# elif 151<=N<=400:
# res = 150*0.4463 + (N-150)*0.4663
# else:
# res = 150*0.4663 + (4... |
nums = [2,5,6,0,0,1,2]
# nums = [4,5,6,7,8,9,0,1,2]
# nums = [8,9,0,1,2,3,4,5,6]
nums = [1,1,1,1,2,1]
target = 2
def search_rotated_sorted(nums, target):
n = len(nums)
left = 0
right = n-1
while left <= right:
mid = (left+right)//2
if nums[mid] == target:
return True
... |
#일정 시간 간격으로 크롤링 및 기타 반복 작업 가능한 예제
import time
import threading
def thread_run():
print('=====',time.ctime(),'=====')
for i in range(1,51):
#개발 하고자 하는 코드
print('Thread running - ', i)
threading.Timer(2.5, thread_run).start()
thread_run()
#threading.Timer(2, thread_run).start() : 메인에서 실행하면 ... |
#JSON===CONVERTER
import json
x = {
"name": "ferdi",
"age": 28,
"city": "l-town"
}
#Convert into JSON
y = json.dumps(x)
#JSON CREATED
print(y) |
# import datetime
# x= datetime.datetime.now()
# print(x)
import datetime
x= datetime.datetime(2020, 5, 7)
# day
# print(x.strftime("%d")) | print(x.strftime("%A")) | print(x.strftime("%a"))
# month
# print(x.strftime("%B")) | print(x.strftime("%b")) | print(x.strftime("%m"))
# # year
# print(x.strftime("%Y")) | p... |
# Learning __init__ (initializer)
class People:
def __init__(self, firstName, age, ):
self.firstName = firstName
self.age = age
def displayPerson(self):
print("Hello, my name is " + self.firstName + ", I am " +
str(self.age) + " years old.")
person1 = People("John"... |
age = 15
if age >= 18:
print(True)
else:
print(False)
#? Operador ternario (ternary)
is_adult = True if age >= 18 else False #Cualquier condición, pero no se pueden igualar variables dentro del operador ternario
print(is_adult)
is_adult = 'Es adulto' if age >= 18 else 'No es adulto'
print(is_adult)
list_a =... |
#!/usr/bin/env python3
def popular_words(text: str, words: list) -> dict:
result = {}
for item in words:
count = 0
for word in text.split(' '):
if item.lower() == word.lower():
count += 1
print(count)
result[item] = count
return result
if __nam... |
#!/usr/bin/env python
lines=[]
while True:
s=raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print(sentence)
|
#!/usr/bin/env python3
def checkio(words: str) -> bool:
count = 0
for index in words.split(" "):
# print(index)
if index.isalpha():
count = count + 1
else:
count = 0
if count == 3:
return True
return False
if __name__ == '__main__':
p... |
#!/usr/bin/env python3
def checkio(number: int)-> int:
mul = 1
for item in [int(digits) for digits in str(number)]:
if item != 0:
mul = mul*item
return mul
if __name__ == '__main__':
print(checkio(123405))
|
#!/usr/bin/env python3
def long_repeat(line):
if not line: return 0
else:
max_repeat = 0
count = 1
for item in range(1,len(line)):
if line[item] == line[item-1] :
count += 1
else: count = 1
print(f'{item} : {count}')
if ma... |
#!/usr/bin/env python3
def between_markers(text:str, begin:str, end:str)-> str:
if begin in text:
begin_index = text.find(begin) + len(begin)
else:
begin_index = 0
if end in text:
end_index = text.find(end)
else:
end_index = len(text)
return text[begin_index:end_ind... |
#!/usr/bin/env python3
def find_message(text: str) -> str:
result= []
s = ""
for letter in text:
if letter.isupper() == True:
result.append(letter)
return s.join(result)
def find_message_2(text):
return ''.join(i for i in text if i.isupper())
if __name__=='__main__':
pri... |
import math
import unittest
import distance
class TestDistance(unittest.TestCase):
def test_euclideanBase(self):
a = [0, 0]
b = [0, 0]
self.assertEqual(distance.euclidean(a, b), 0)
a = [1, 0]
b = [0, 0]
self.assertEqual(distance.euclidean(a, b), 1)
a = [0,... |
import unittest
import binarysearchtree
class BinarySearchTreeTests(unittest.TestCase):
def test_basic(self):
t = binarysearchtree.Node(10)
assert(t.list() == '(10)')
t.add(5)
t.add(7)
t.add(6)
assert(t.list() == '((5((6)7))10)')
assert(t.search(7) is not ... |
a,b=0,1
print(a,b,end=" ")
num=int(input("\n\nEnter the number to check if in fib?"))
while True:
c=a+b
print(c,end=" ")
if c<=num:
if c==num:
print("\nYes! It is in the fib series")
break
else:
print("\n NO! It is not in the fibonacci series")
break
... |
print("************************************************")
print("Sistema para reconocer que numero es mas grande")
print("************************************************\n ")
nu = int(input("Por favor, ingrese el primer numero: "))
nd = int(input("Por favor, ingrese el segundo numero: "))
nt = int(input("Por favor, i... |
def rectangle_area(a, b):
if(a>=0 and b>=0):
area = a*b
print("Pole prostokata wynosi:")
print(area)
else:
print("Blad! Podaj nieujemna wartosc dlugosci boku")
return
rectangle_area(3.23,1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.