text stringlengths 37 1.41M |
|---|
#python 列表
var1=['peng','man','yi']
var2='peng'
if var2 in var1:
print 'in'
else:
print 'not in'
print var1
var1[1]='man'
print var1
var3=['19891006',29]
print var1+var3
for x in var1:
print x
#python截取列表
print var1[1:]
print len(var1)
print max(var1)
print min(var1)
var4=[20,30,10,34,53]
print max(var4)
pr... |
from scipy.stats import truncnorm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
def simulate_data() -> list:
"""
Generate data for Monte Carlo Simulation
:return: a list of data
>>> np.random.seed(1)
>>> data=simulate_data()
>>> print(data[1])
... |
#
# Write a (recursive) method to compute all the permutations of a string.
#
# From the recursion section in Cracking the Coding Interview.
# https://stackoverflow.com/questions/13109274/python-recursion-permutations?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
#
# from itertools import pe... |
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
max_index1=0
for first in range(n):
if max_index1==0 or numbers[first]>numbers[max_index1]:
max_index1=first
max_index2=0
for second in range(n):
if second!=max_index1 and (max_index2==0 or numbers[se... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 07:06:48 2019
@author: souma
"""
class Employee:
# Define class variables
raise_amount = 1.04
num_employees = 0
def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay
self.email = ... |
import random
from collections import Counter
from typing import List
Scores={
"Straight":1500,
"Three Pairs" : 1500,
(1,1):100,
(1,2):200,
(1,3):1000,
(1,4):2000,
(1,5):3000,
(1,6):4000,
(2,3):200,
(2,4):400,
(2,5):600,
(2,6):800,
(3,3):300,
(3,4):600,
(3,... |
# imports
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Read & sort dataset
db = pd.read_csv("data.csv")
db = db.sort_values(by=["month"],ascending=True)
db = db[db.number_people != 0]
# temp variables
indexW=0
countW=0
avgW = [0] * 5
indexF=0
countF=0
avgF = [0] * 5
# get avg of ppl per ... |
class Actor():
def list_actor():
actor=[]
while True:
name=input("please type the actor name : ")
actor.append(name)
if int(input("Do you want to continue? 0-1"))==0:
break
return actor
|
#Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
#Example:
#Input: [0,1,0,3,12]
#Output: [1,3,12,0,0]
from typing import List
def moveZeroes(nums: List[int]) -> None:
j = 0
for i in range(0, len(nums)):
if nums[i] !... |
from BinaryTree import BinaryTree
from Bacteria import Bacteria
import random
#Original values to pass in
_LENGTH = 1
_POS_X = 0
_POS_Y = 0
_AGE = 0
_SPACE_PER_LEVEL = 10
_EMPTY_LINE = ""
for i in range(0, _SPACE_PER_LEVEL):
_EMPTY_LINE += ' '
_DEBUG = True
_TIME = 3 #Units of time that simulation runs
_REPRODU... |
goal = int(input("What is your savings goal: "))
deposit = int(input("What is your monthly deposit: "))
interest = int(input("What is the annual interest rate: "))
print("")
total = 1000
month = 1
while total <= goal:
monthly_interest = total / 120
format_total = "{:.2f}".format(total)
print(f"Month {month}: Yo... |
r = float(input("반지름 입력 : "))
def circle_square(r):
x = r**2 * 3.14
print('원의 면적은 {}이다.'.format(x))
return r
circle_square(r) |
num = input("Enter Your Number :")
numb = int(num)
if(numb>=0):
print(numb, " is Positive Number")
else:
print(numb," is negetive Number") |
program_terminate = False
while not program_terminate:
n1=input("Enter num1 value :\n")
n2=input("Enter num2 value :\n")
n1=int(n1)
n2=int(n2)
con = input("Enter The method like 'quit,sub,add' only one from here :\n")
while True:
if con=="quit":
program_terminate=True
... |
marks = input("Enter your marks :")
marks = int(marks)
if marks>=80:
grade="A+"
elif marks>=70:
grade="A"
elif marks>=60:
grade="A-"
elif marks>=50:
grade="B+"
elif marks>=40:
grade="B"
else:
grade="F"
print("Your Grade is :",grade) |
#Shitty code to generate input string randomly
import string
import random
inp=input("Enter your string without space: ")
out=''
con=0
total=0
while(inp != out ):
total+=1
randomLetter = random.choice(string.ascii_letters)
print(randomLetter)
if (randomLetter==inp[con]):
out+=randomLetter
... |
import numpy as np
import pandas as pd
def suited_to_int(s):
"""returns 1 if suited and 0 if unsuited
Args:
s (string): yes or no, input by user
Returns:
int: 1 if suited (True), 0 if unsuited (False)
"""
s = s[0].upper()
if s == 'Y':
return 1
else:
... |
def findTheNumbers(a):
mydict={}
for i,ele in enumerate(a):
if ele not in mydict: mydict[ele] = list()
mydict[ele].append(i)
if len(mydict[ele])==2:
del mydict[ele]
return sorted(list(mydict.keys()))
if __name__ == '__main__':
a = [1, 3, 5, 6, 1, 4, 3, 6]
print f... |
# Globals for the directions
# Change the values as you see fit
EAST = 'east'
NORTH = 'north'
WEST = 'west'
SOUTH = 'south'
class Robot:
def __init__(self, direction=NORTH, x=0, y=0):
self.direction = direction
self.x = x
self.y = y
@property
def coordinates(self):
return ... |
def calculateYearlyPayment(balance, annualInterestRate, monthlyPayment):
"""
balance - integer
annualInterestRate - float
montlhyPamentRate - float
return balance after paying minimum monthly payment, for one year
"""
monthlyInterestRate = annualInterestRate / 12.0
unpaidBalance = 0
for month in rang... |
# -*- coding: utf-8 -*-
ent=raw_input().split()
dados=[int(ent[0]),int(ent[1])]
while(dados[0]!=dados[1]):
if dados[0]>dados[1]:
print 'Decrescente'
else:
print 'Crescente'
ent=raw_input().split()
dados=[int(ent[0]),int(ent[1])] |
# -*- coding: utf-8 -*-
lista=[]
for i in range(20):
lista.append(float(input()))
lista.reverse()
for i,item in enumerate(lista):
print 'N[%i] = %i'%(i,item)
|
# -*- coding: utf-8 -*-
n=int(input())
resposta=""
for i in range(n):
p=int(input())
resposta=""
if p!=0:
if p%2==0:
resposta= resposta+"EVEN"
else:
resposta= resposta+"ODD"
if p>0:
resposta=resposta+" POSITIVE"
else:
resposta= res... |
# -*- coding: utf-8 -*-
n=int(input())
for i in range(n):
v=raw_input().split()
print "%.1f" %((float(v[0])*2+float(v[1])*3+float(v[2])*5)/10)
|
# -*- coding: utf-8 -*-
def ganhou(lista):
lis=[int(lista[0]),int(lista[1])]
if lis[0]<lis[1]:
return 'grem'
if lis[0]>lis[1]:
return 'inter'
return 'emp'
total=0
gre=0
inter=0
emp=0
cont=1
while (cont!=2):
n=raw_input().split()
ganhador=ganhou(n)
if ganhador=='grem':
... |
# -*- coding: utf-8 -*-
r=1
while(r!=2):
if(r==1):
i=0
soma=0
err=0
while (err<2 or i<2):
n=float(input())
if (10>=n>=0):
soma+=n
i+=1
else:
err+=1
print 'nota invalida'
if... |
# -*- coding: utf-8 -*-
senha=int(input())
while(senha!=2002):
print 'Senha Invalida'
senha=int(input())
else:
print 'Acesso Permitido' |
# -*- coding: utf-8 -*-
n1,n2,n3,n4=raw_input().split(" ")
n1=float(n1)
n2=float(n2)
n3=float(n3)
n4=float(n4)
media=(2*n1+3*n2+4*n3+n4)/10
print "Media: %.1f" %media
if media>=7.0:
print "Aluno aprovado."
else:
if media<5:
print "Aluno reprovado."
else:
print "Aluno em exame."
ne=fl... |
# -*- coding: utf-8 -*-
arvore={"vertebrado":{"ave":{"carnivoro":"aguia","onivoro":"pomba"},
"mamifero":{"onivoro":"homem","herbivoro":"vaca"}},"invertebrado":{
"inseto":{"hematofago":"pulga","herbivoro":"lagarta"},"anelideo":{"hematofago":"sanguessuga","onivoro":"minhoca"}}}
n1=raw_input()
n2=raw_input()
n3=raw_input(... |
def merge_sort(x):
"""
Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or
has one item, it is sorted by definition (the base case). If the list has more than one item,
we split the list and recursively invoke a merge sort on both halves. Once the two ha... |
#-------------------------------------------------#
# Title: Mailroom part 2
# Dev: Rlarge
# Date: 2/13/2019
# ChangeL/og: (Who, When, What)
# RLarge, 01/31/2019, Created Script
# RLarge, 02/13/2019, Modified script with
# Exceptions and Comprehensions
#-------------------------------------------------#
# Imp... |
'''
When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False... |
import math
#Las funciones tienen un nombre y se declaran con la palabra raservada def y devuelven un valor usando la palabra
#return. Se puede pasar una lista de argumentos o parametros: bien por posiciones o por clave
#Funcion es conjunto de linesa de codigo agrupadas (bloque de codigo) que funcionen como una unida... |
# Tanto las Tumpla como las listas son conjuntos ordenados de elementos, no asi los diccionarios.
# Que son las listas:
# Estructura de datos que nos permite almacenar grand cantidad de valores(equivalente a los array en todos lenguajes
# de programacion.
# En Python las listas pueden guardar diferentes tipos de... |
def menu():
print('----- Gestión de aeropuertos ------')
print('-----------------------------------')
print()
print('1. Cargar pilotos.')
print('2. Cargar aeropuertos.')
print()
print('3. Listar pilotos')
print('4. Listar aeropuertos.')
print('5. Listar rutas.')
print()
pri... |
# Los conjunto o sets son colecciones no ordenadas de elmentos no repetidos. Los conjuntos pueden crearse de dos formas diferentes
# Mediante una lista de elementos entre llaves { }
# Mediante la funcion set()
s1 = set([3, 3, 3, 1, 1, 1, 2])
s2 = {3, 5, 6, 7, 7, 1, 1, 1, 2}
# Los conjuntos en Python admiten l... |
FillerList1 = ["all", "no", "some"]
FillerList2 = ["are", "are not", "have", "have no", "is", "is not"]
def FindType(In1, In2, S1, S2): # Both have to be split!
if In1[S1] == "all":
if In2[S2] == "some" or In2[S2] == "no":
Word_List[0] = 2
else:
Word_List[0] = 0 # CAN BE 2... |
import functools
import operator
def flattenList(l,*m):
'''
flatten a list l, along with optionally expanding other list of the same length as l in the same fashion, for instance if we want to flatten l and m is another list where each entry corresponds to an entry in l, then we would expand m by duplicating ... |
#coding=utf-8
'''
python 中 一个字符串相对应一个字符数组
'''
name='abcdefghij中文'
print("name=%s"%name)
print()
print("name[0]=%s"%name[0])
print("name[1]=%s"%name[1])
print("name[len(name)-1]=%s"%name[len(name)-1])
print("name[-1]=%s"%name[-1])
print("name[-5]=%s"%name[-5])
'''
字符串切片
'''
print("name[2:4]=%s"%name[2:4])#包头不包尾
print("n... |
#coding=utf-8
#需求:创建一个列表,里面包含10~27
#方法一
a=[]
i=10
while i<=27:
a.append(i)
i+=1
print(a)
print("-"*40)
'''
range 注意下面表达式在2和3中不同表现
在python2中range存在风险,比如range(1,9999999999)
在python3中避免了这个风险,在使用时才真正开辟内存
'''
print("range(10)=%s"%range(10))
print("range(10,15)=%s"%range(10,15))
print("range(10,15,2)=%s"%range(10,15,2))
pr... |
#coding=utf-8
def func1(n):
if n>1:
return n*func1(n-1) # return 4*func1(3)=4*3*func1(2)=4*3*2*func1(1)
else:
return 1
n=int(input("请输入一个数字:"))
print(func1(n))
|
#coding=utf-8
names = [11,22,33,44,55]
print(names)
i=int(input("请数据值:"))
for name in names:
if i==name:
print("%d在列表names中"%i)
break #当跳出后,就跳出for循环,else也不执行
else: #当for循环♻️执行完成后执行eles
print("%d不在列表names中"%i)
'''
for else 结合break使用是个不错的设计
java中没有,在判断一个集合中是非有某变量时,不需要定义一个booble,在找到后设置booble=t... |
#coding=utf-8
import numpy as np
a = np.array([[1,2],[3,4],[1,1]])
b = np.array([[2],[4]])
print(a)
print('----------')
print(b)
print('----------')
print(a.dot(b))
print('----------')
print(np.dot(a,b))
'''
矩阵乘法 前提 a的列数 = b的行数
结果矩阵的行数=a的行数 列数=b的列数
结果矩阵的m,n的值=a第m行 与 b第n列 分别相乘 然后相加
'''
|
# 6-5. Rivers: make a dictionary containing three major rivers and the country
# each river runs through. one key-value pair might be 'nile' : 'egypt'.
# use a loop to print the name of each country included in the dictionary.
# rivers = {'nile': 'egypt', 'hudson': 'usa', 'volga': 'russia', 'mississippi': 'usa', 'tham... |
from tkinter import *
class MainGUI:
def __init__(self):
window = Tk()
window.title('Eight Queens')
self.main_frame = Frame(window) # frame to hold the board
self.main_frame.pack()
# Queen positions
queens = 8 * [-1] # queens are placed at (i, queens... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 15 13:21:43 2019
@author: Erin Canada
Project # 2 is to implement linear regression for binary classification
from scratch (as we've been discussing / working on for the past several
lectures). Minimize the logistic regression objective function in two
differ... |
# hand-grenade sort, a near-enough is good enough implementation of quicksort
import random
randlist = []
for x in range(10):
randlist.append(random.randint(1, 20))
def hgSort(inlist):
l = []
e = []
g = []
hg = []
scannedOnce = False
if len(inlist) > 1:
pivot = inlist[0]
... |
#-*- coding:utf-8 -*-
#filename: quick_sort.py
import random
def swap(A, i, j):
A[i], A[j] = A[j], A[i]
#print(A)
def Partition(A, left, right):
pivot = A[right]
tail = left - 1
for i in range(left, right):
if A[i] <= pivot:
tail += 1
swap(A, tail, i)
swap(A, ta... |
import pandas as pd
import numpy as np
# read the excel file
file_path = 'Master.xlsx'
df = pd.read_excel(
file_path, index_col=None, header=None)
# initialize the variable for do this task
tables = []
split_tables = []
update_dates = {}
start_index = {}
end_index = {}
current_table = None
# find start row, end ... |
from collections import deque
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
# Simple Version, using queue
# class Solution:... |
from typing import List
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
queue = deque([(0, root)])
... |
'''
Ivor Zalud
CS 5001, Fall 2020
Main function for the checkes game
'''
import turtle
from gamestate import GameState
NUM_SQUARES = 8 # The number of squares on each row.
SQUARE = 50 # The size of each square in the checkerboard.
SQUARE_COLORS = ("light gray", "white")
PIECE_RADIUS = SQUARE / 2
BOARD_SIZE = NUM_SQ... |
S = 'A man, a plan, a canal: Panama '
#S = "race a car"
#S = ''
def validate(S):
res = ''
for s in S:
if s.isalpha():
res += s.lower()
return res == res[::-1]
print validate(S)
# Submission Result: Accepted
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
... |
class Solution:
# @param A, a list of integers
# @return a boolean
def canJump(self, A):
n=len(A)
i=0
while True:
#print i
if i>=n-1: return True
if A[i] ==0 : return False
i+=A[i]
return False
|
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert(self, intervals, newInterval):
... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
# keep all node in a list, then remove le... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
A=self.trav(root)
for i in range(1,len(A)):
... |
A = [
[2],
[3,4],
[3,2,7],
[4,2,6,3],
[5,7,5,1,3]
]
n = len(A)
def min_path_sum(A, n, sum1=0, min_sum=None, i=0, j=0):
''' recursive, working like a complete binary tree
'''
if i >= n:
if min_sum == None or sum1 < min_sum:
min_sum = sum1
else:
sum1 += A[i][j]
min_sum = min_path... |
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
x,y,z=0,0,0 # x,y,z for number shows are 1,2,3 times
for a in A:
y=y|x & a # if a shows twice, y include a, x & a includ a, assign to y
x^=a # for first time, x includ a
z=x&y # if x and y bo... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
if not root: return []
... |
A = [ ['A', 'B', 'C', 'E' ],
['S', 'F', 'C', 'S' ],
['A', 'D', 'E', 'E' ]
]
s ='SFDECCESC'
def find_path(A, s):
n = len(A)
m = len(A[0])
for i in range(n):
for j in range(m):
if walk(A, s, i, j, n, m, res=False, k=0, ss='', coor=[]):
return True
return False
def walk... |
class Solution:
# @return a boolean
def isValid(self, s):
stack=[]
n=len(s)
for i in range(n):
if s[i]=='(': stack.append(s[i])
elif s[i]=='{': stack.append(s[i])
elif s[i]=='[': stack.append(s[i])
elif s[i]==')' and len(stack)>0:
if stack[-1]=='(': sta... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
#def hasPathSum(self, root, sum):
def h... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if not head or not head.next: return head
n=head
... |
A=[[1,3],[2,6],[10,19],[5,8]]
def merge(A):
B = sorted(A, key = lambda x:x[0])
n = len(A)
res = []
current_interval = B[0]
for i in range(1, n):
if B[i][0] <= current_interval[1]: # overlapping
if B[i][1] > current_interval[1]:
current_interval[1] = B[i][1]
else:
res.append(current... |
from sys import stdin
from Token import *
class Lexer:
def __init__(self):
self.inp = stdin
self.the_string = self.inp.read()
#self.the_string = str(input())
#self.the_file = open('sample.txt')
#self.the_string = self.the_file.read()
self.the_size = len(sel... |
#!/usr/bin/env python
# coding: utf-8
# # Assignment 1
# ## Python Basic Programs
# ### 1. Print Hello world! :
# In[ ]:
print("Hello world!")
# ### 2. Declare the following variables: Int, Float, Boolean, String & print its value.
#
# In[ ]:
a = 10
print(a, "is of type", type(a))
b = 5.0
print(b, "is a ty... |
#Q1 Reverse the whole list using list methods.
print("<--solution 1-->")
list=[1,2,3,4,5]
list.reverse()
print(list)
#Q2 Print all the uppercase letters from a string.
print("<--solution 2-->")
string= "PULKIT JOHAR"
for ch in string :
if ch.isupper():
print(ch)
#question 3 Split the user input on... |
def computepay(h,r):
if h <= 40:
return h * r
else:
return ((h-40) * (r * 1.5)) + (40 * r)
hrs = float(input("Enter Hours: "))
rs = float(input("Enter Rate: "))
p = computepay(hrs,rs)
print("Pay",p)
|
def sieve(limit: int) -> list:
if limit < 2:
return []
primes = []
nums = list(range(2, limit+1))
for index in range(2, limit+1):
if index in nums:
primes.append(index)
for num in nums:
if num % index == 0:
nums.remove(num)
... |
def is_isogram(string) -> bool:
char_set = set()
for char in string.lower().replace("-","").replace(" ", ""):
if char in char_set:
return False
char_set.add(char)
return True
|
__author__ = 'nunoe'
class Location(object):
def __init__(self, x, y):
"""
:param x: float, horizontal coordinate
:param y: float, vertical coordinate
"""
self.x = x
self.y = y
def move_to(self, delta_x, delta_y):
"""
:param delta_x: float, dis... |
"""
URL Shortener
Description:
You are asked to develop code for a URL shortening
service similar to https://goo.gl/. Users of this
service will provide you URLs such as https://en.
wikipedia.org/wiki/History_of_the_Internet.
As a result your service should return a shortened
URL such as http://foo.bar/1xf2. In t... |
#coding=utf-8
import re
def word_tokenize(text): return re.findall(r'\w+', text.lower())
##removes non non-alphanumeric characters based on re
def re_nalpha(str):
pattern = re.compile(r'[^\w\s]', re.U)
return re.sub(r'\n','',re.sub(r'_', '', re.sub(pattern, '', str)))
##tokenization in uni- to n-grams,a function... |
def test(a, b, c):
if a == b or b == c or c == a:
return True
else:
return False
Answer = test(5,6,7)
print (Answer)
#Extra Credit
def Test(a,b,c):
if a == b or b == int(c) or int(c) == a:
return True
else:
return False
Result = Test(7,8,"8")
print(Result) |
import math
def lcm(a,b):
'''
Lowest common multiple
'''
return a*b/gcd(a,b)
def gcd(a,b):
'''
Greatest common divisor
'''
if a%b == 0:
return b
else:
return gcd(b,a%b)
def sieve(MAXN):
'''
Sieve of Eratosthenes up to MAXN (inclusive)
'''
is_prime ... |
def is_palindrome(s):
return s[::-1] == s
def check(n):
return is_palindrome(str(n)) and is_palindrome(bin(n)[2:])
ans = 0
for n in xrange(1,1000000):
if check(n):
ans += n
#print n
print ans |
def get_digit_string(digits):
string = ""
start = -1
for i in xrange(5,10):
if start == -1 or digits[i] < digits[start]:
start = i
cur = start
for i in xrange(5):
string += str(digits[cur])
string += str(digits[cur-5])
string += str(digits[(cur-... |
import math
def is_pent(x):
det = 1 + 24*x
det_root = int(math.sqrt(det))
if (det_root+1)**2 == det:
det_root += 1
n = (1 + det_root)/6
return n*(3*n-1)/2 == x
def is_hex(x):
det = 1+8*x
det_root = int(math.sqrt(det))
if (det_root+1)**2 == det:
det_root += 1
... |
import math
def is_tri(t):
root = int(math.sqrt(1+8*t))
if (root+1)*(root+1) == 1+8*t:
root += 1
if root*root != 1+8*t:
return False
n = (-1+root)/2.0
return abs(n-int(n)) < 1e-6
def convert(word):
t = 0
for char in word:
t += ord(char)-ord('A')+1
return t
an... |
# Python 3.7
# This Program tells the diameter from one Node of the tree to another
# By Yusuf Ali
# Finds the Height of the tree
class TreeHeight:
def __init(self):
self.h = 0
# Creates the Node
class Node:
def __init__(self, data):
self.data = data
self.left = self.r... |
# https://leetcode.com/problems/most-common-word/
import re
from collections import Counter
def find_most_common_word(paragraph, banned):
words = re.findall(r'\w+', paragraph.lower())
allowed_words = [w for w in words if w not in set(banned)]
return Counter(allowed_words).most_common()[0][0]
paragra... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
... |
class Solution(object):
def accountsMerge(self, accounts):
"""
:type accounts: List[List[str]]
:rtype: List[List[str]]]
n = len(accounts)
email2name = dict()
TODO https://leetcode.com/problems/accounts-merge/submissions/
""... |
"""
https://leetcode.com/problems/reorder-data-in-log-files/
"""
class Solution(object):
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
digits = []
letters = []
# divide logs into two parts, one is digit logs, the other is lette... |
"""CSC148 Lab 4: Abstract Data Types
=== CSC148 Winter 2021 ===
Department of Mathematical and Computational Sciences,
University of Toronto Mississauga
=== Module Description ===
In this module, you will write two different functions that operate on a Stack.
Pay attention to whether or not the stack should be modifi... |
"""Lab 7: Trees and Recursion, Task 3
=== CSC148 Winter 2021 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This module contains a basic automatic random tiling generator that you will
complete for Task 3 of this lab.
There's quite a bit to read here--... |
"""CSC148 Lab 4: Abstract Data Types
=== CSC148 Winter 2021 ===
Department of Mathematical and Computational Sciences,
University of Toronto Mississauga
=== Module Description ===
In this module, you will develop an implementation of the Queue ADT.
It will be helpful to review the stack implementation from lecture.
... |
import random
import os
def read(filepath = "./archivos/data.txt"):
words = []
with open(filepath, "r", encoding = "utf-8") as f:
for line in f:
words.append(line.strip().upper())
return words
def run():
data = read(filepath = "./archivos/data.txt")
#Uso de modulo random p... |
n = int(input())
for i in range (n,0,-1):
if (n%i == 0):
print(int(n/i),end=" ") |
import sys
sys.stdin = open("input.txt",'r')
def binary_search(pages,key):
start = 1
end = pages
cnt = 0
while start <= end:
middle = int((start + end) / 2)
cnt+=1
if key == middle:
return cnt
elif key > middle:
start = middle
else:
... |
result = []
data = [1,2,3,4,5]
def combination(n,r,now=0,cnt=0,temp=None):
global result
if temp == None:
temp = []
if cnt == r:
result.append(temp)
elif n-now < r-cnt:
return
elif now < n:
# 선택
new_temp = temp + [data[now]]
combination(n, r, now + 1, ... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python3
import pathlib
def tree(root_path_obj):
assert root_path_obj.is_dir()
items = list()
for item in root_path_obj.resolve().iterdir():
if item.is_dir():
items.extend(tree(item)) # recursion!
else:
items.append(item)
... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python3
import PyPDF2
import pathlib
# --- ROTATE CONTENTS OF A PDF FILE AND SAVE TO ANOTHER ---
def rotate_clockwise(src_pdf_path, target_pdf_path, rotation_angle):
assert isinstance(src_pdf_path, str)
assert isinstance(target_pdf_path, str)
assert isinstance(rot... |
'''
주어진 리스트 데이터를 이용하여 3의 배수의 개수와 배수의 합을 구하여 아래와 같이 출력하세요
data = [1, 3, 5, 8, 9, 11, 15, 19, 18, 20, 30, 33, 31 ]
'''
data = [1, 3, 5, 8, 9, 11, 15, 19, 18, 20, 30, 33, 31]
#갯수를 구할 변수
count = 0
#합계를 구할 변수
sum = 0
for multiple in data :
# print(multiple)
if multiple%3==0 :
#print("3의 배수:" , multiple, e... |
#Python sayı tahmin oyunu
#Python number guess game
#You can copy that file as you want.
#Its ok for me :D
#Dosyayı istediğiniz gibi kopyalayabilirsiniz.
#Benim için sorun yok :D
sayi=50
a=1
denemeler = 0
while a==1:
if denemeler <= 5:
denemeler+=1
tahmin=input("tuttuğum bir sa... |
import sqlite3 as sql
db = sql.connect('dtb.db')
cur = db.cursor()
print("Welcome to our store. You can buy credits there.")
print("""
Prices:
1 credit = 1 ¢
""")
cur.execute("SELECT credit FROM credits")
beforeCredits = cur.fetchall()[0][0]
request = int(input("How many credits you want to buy?... |
#! /usr/bin/python
#
class BinaryHeap:
def __init__(self):
self.heap_list = [0] # do not init empty
self.current_size = 0
def insert(self, node):
self.heap_list.append(node)
def find_min(self):
print 'foo'
def delete_min(self):
print 'foo'
def size(self):
return len(self.help_list)... |
#! /usr/bin/python
class BinaryTree:
def __init__(self, root):
self.root = root
self.left_child = None
self.right_child = None
def insert_left(self, node):
new_tree = BinaryTree(node)
if self.left_child == None:
self.left_child = new_tree
else:
new_tree.left_child = self.left_... |
for i in range(6): #5줄을 출력할 수 있는 반복문
for n in range(5,i-1,-1): #숫자앞의 공백을 출력하는 반복문
print(end=" ")
for j in range(1,i+1):
print(j,end="")
print()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.