text stringlengths 37 1.41M |
|---|
#
#
#
# def reverse_list(l):
# '''
#
# :param l:list
# :return: l
# '''
# i,j = 0,len(l) - 1
# while i < j:
# l[i],l[j] = l[j],l[i]
# i += 1
# j -= 1
# return l
#
# def max_and_min(l):
# '''
#
# :param l: list:l
# :return: min and max
... |
class Solution():
def isPowerOfThree(self,n):
import math
if n == 0:
return False
elif 3**int(round(math.log(abs(n),3),0)) == n:
return True
else:
return False
my = Solution()
print(my.isPowerOfThree(-27)) |
# 选择排序
# 最优时间复杂度O(n^2)
# 最坏时间复杂度O(n^2)
# 稳定性:不稳定(考虑升序每次选择最大的情况)
def select_sort(alist):
n = len(alist)
for i in range(n-1):
mix_index = i
for j in range(i+1,n):
if alist[mix_index] > alist[j]:
mix_index = j
alist[i],alist[mix_index] = alist[mix_inde... |
# 面向对象编程有四大概念:封装、抽象、多态、继承
# 他们共同构成了面向对象编程的四大支柱
# class Shape():
# def __init__(self,w,l):
# self.width = w
# self.len = l
#
# def print_size(self):
# print("{} by {}".format(self.width,self.len))
#
# class Square(Shape):
# def area(self):
# return self.width * sel... |
# 如果a + b + c = 1000,且a^2 + b^2 = c^2(a,b,c为自然数),如何求出所有a,b,c可能的组合?
from time import *
begin = time()
for a in range(0,1001):
for b in range(0,1001):
c = 1000 - a - b
if a**2 + b**2 == c**2:
print('a,b,c:%d, %d, %d'%(a,b,c))
end = time()
print('time:%d'%(end - begin)) |
# 该模块提供了很多有关数学的运算方法
import math
## 一.幂与平方根
# pow(x,y):返回 x 的 y 次方,返回值为浮点数
print(math.pow(2,4))
# ldexp(x,i):返回 x * (2 ** i),返回值为浮点数
print(math.ldexp(2,4))
# sqrt(x):求x的算术平方根
print(math.sqrt(2))
# factorial(x):求x的阶乘
print(math.factorial(5))
# hypot(x,y): 得到 x**2 + y**2 的算术平方根,返回值为浮点数
print(math.hyp... |
def find_even_index(list):
for i in range(len(list)):
left_sum = 0
right_sum = 0
if i == 0:
for a in range(i+1,len(list)):
right_sum += list[a]
if right_sum == 0:
return i
elif i > 0 and i < len(list) - 1:
... |
class Stack():
'''栈'''
def __init__(self):
self._list = []
def push(self,item):
'''添加一个新的元素到栈顶'''
self._list.append(item)
def pop(self):
'''弹出栈顶元素'''
print(self._list.pop())
def peek(self):
'''返回栈顶元素'''
if self._list:
r... |
class Solution():
def fizzBuzz(self,n):
new_list = ['1','2']
for i in range(3,n + 1):
if i % 3 == 0 and i % 5 == 0:
new_list.append('FizzBuzz')
elif i % 3 == 0:
new_list.append('Fizz')
elif i % 5 == 0:
new_l... |
# 3.Даны два списка чисел.
# Посчитайте, сколько различных чисел
# содержится одновременно как в первом списке,
# так и во втором.
list_1 = [1, 2, 3, 4, 5, 6, 12]
list_2 = [1, 6, 8, 9, 2]
res = [x for x in list_1 + list_2 if x not in list_1 or x not in list_2]
print('В списках 1 и 2 ', len(res), 'различных чисел')
|
#!/usr/bin/env python
'''
Anything after '#' on the line is ignored by the py interpreter
Except first line # followed by ! which is called hashbang/sha-bang.
In *nix, when a script with a shebang is executed, the program loader
parses the rest of the script's initial line as an interpreter
directive.
'''
a = 5
"""... |
def fib(n):
sequence = [1, 1]
while (len(sequence) < n):
i = len(sequence)
sequence.append(
sequence[i-1] +
sequence[i-2]
)
return sequence[:n]
# fib(2) -> [1, 1]
# fib(5) -> [1, 1, 2, 3, 5]
# fib(10) -> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] |
print("Enter the number of elements")
n=int(input())
l=[0]*n
ans=-1
print("Enter the elements")
for i in range(n):
l[i]=int(input())
print("Enter the element to search")
k=int(input())
for i in range(n):
if k==l[i]:
ans=i
if ans==-1:
print ("Element not found")
else:
print("The position of the element is : ")
p... |
def towerOfHanoi(numberOfDisks, fromRod, toRod, auxRod):
if numberOfDisks == 1:
print("Move {} from {} to {}".format(numberOfDisks,fromRod,toRod))
return
towerOfHanoi(numberOfDisks-1,fromRod,auxRod,toRod)
print("Move {} from {} to {}".format(numberOfDisks,fromRod,toRod))
towerOfHanoi(num... |
x=0
sum=0
while x<99:
x=x+3
sum=sum+x
print(x)
print(sum) |
# Waveform.py -- a set of functions required for basic DSP
#
# normaliseRMS: adjust root-mean-squre (RMS) of the signal to the target RMS.
# snr: compute speech-to-noise ratio of given speech and noise signals.
# rms: compute RMS of the signal
#
# Python (c) 2019 Yan Tang University of Illinois at Urbana-Champaign (U... |
N=int(input())
result = 0
for n in range(N+1):
result += n
print(result)
N = int(input())
for i in range(N):
for j in range(1, N-i):
print(" ", end="")
for j in range(i*2+1):
print("*", end="")
print()
N = int(input())
for i in range(N):
for j in range(1,N-i):
print(" ",e... |
num1 = 100
num2 = 20
log_result = num1 >=50 or num2 <=10
print(log_result)
log_result = num1 >=50
print(log_result)
log_result = not(num1 >= 50)
print(log_result)
# 변수에 값 할당(=)
i = tot = 10 # i =10; tot = 10
i += 1 # i = i + 1
tot +=i # tot = tot + i
print(i, tot)
#같은줄에 중복 출력
print('출력1', end=' , ') # end='구분자'
prin... |
class Account:
#(1) 은닉 멤버변수
__balance = 0 #잔액
__accName = None # 예금주
__accNo = None # 계좌번호
#(2) 생성자 : 멤버변수 초기화
def __init__(self, bal, name, no):
self.__balance = bal # 잔액초기화
self.__accName = name #예금주
self.__accNo = no # 계좌번호
#(3) 계좌정보 확인 : Getter
def getBalanc... |
class MyClass1:
var = "안녕하세요"
def __init__(self, var):
self.var = var
def sayHello(self):
print(self.var)
obj = MyClass1("반갑습니다")
print(obj.var) #ERROR
obj.sayHello()
# 생성자 추가 - 값을 새로운 값으로 class 를 instance 하게
# 바꿔주세요 |
lista = [1, 10]
arquivo = open("teste.txt","r")
# Qual será a tentativa a ser realizada
try:
texto = arquivo.read()
divisao = 10/1
numero = lista[1]
except ZeroDivisionError: # Definindo a exceção
print("Não é possivel realizar uma divisao por 0")
except IndexError:
print("Erro ao acessar um indi... |
a = int(input("Insira um número: "))
divisao = 0
for x in range(1, a+1):
resto = a % x
print(x, resto)
if resto == 0:
divisao += 1
if divisao == 2:
print("Número {} é primo".format(a))
else:
print("Número {} não é primo".format(a))
|
def recursion(list):
if list == '':
return 0
else:
return 1 + recursion(list[:-1])
print recursion("harshdeep") |
score = 78
if score > 90:
grade = "A"
elif score > 80:
grade = "B"
elif score > 70:
grade = "C"
elif score > 60:
grade = "D"
else:
grade = "F"
print(grade)
dayOfWeek = 2
if dayOfWeek == 1:
day = "Monday"
elif dayOfWeek == 2:
day = "Tuesday"
elif dayOfWeek == 3:
day = "Tuesday"
elif d... |
#!/usr/bin/env python3
file = open("Python_05.txt","r")
contents = file.read()
#print(contents)
splitlist = contents.split('\n') #split outputs as a list, also gets rid of what you split on
#print(splitlist)
for item in splitlist:
print(item.upper())
|
#!/usr/bin/env python3
import sys
for i in range(int(sys.argv[1]),(int(sys.argv[2])+1),1):
if i%2 == 1:
print(i)
|
#!/usr/bin/env python3
input = open("Python_05.txt","r")
output = open("Python_05_uc.txt","w")
contents = input.read()
#splitlist = contents.split('\n') why no longer need to split?
for item in contents:
output.write(item.upper())
input.close()
output.close()
print("Wrote 'Python_05_uc.txt'")
|
def intersection(arrays):
"""
YOUR CODE HERE
"""
_list = set(arrays[0])
for i in range(len(arrays)):
_list = list(set(_list) & set(arrays[i]))
# result is a list of the intersecting values
return _list
if __name__ == "__main__":
arrays = []
arrays.append(list(ran... |
from turtle import Turtle, Screen
import random
import time
WIDTH = 500
HEIGHT = 400
class Race_Turtle:
def __init__(self,name,index):
self.obj = Turtle(shape= "turtle")
self.obj.color(name)
self.obj.penup()
self.obj.shapesize(stretch_wid=1)
self.obj.goto(x=-(WIDTH/2), y= -... |
def main():
sum = 0
for num in range(1,1000):
if(num%3 == 0 or num%5 == 0):
sum += num
print sum
if __name__ == '__main__':
main()
|
# import datetime
from datetime import datetime
# class spy
# with detsils of name ,salutation,age ,rating as the argument
# self is used for calling in constructor function
class Spy:
def __init__(self, name, salutation, age, rating):
self.name = name
self.salutation = salutation
self... |
class Solution:
def isMatch(self, text:str, pattern:str):
""" memo
python3 ~ 60ms
"""
memo = {}
def dp(i, j):
# if (i,j) in memo:
# print('used memo',i,j) # so it's faster
if (i,j) not in memo:
_text = text[i:]
... |
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
root = ListNode(0)
p = root
while l1 or l2:
if not l1:
node = ListNode(l2.val)
l2 = l2.next
... |
class BinaryTree(object):
def __init__(self, rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeftChild(self, obj):
if self.leftChild == None:
self.leftChild = BinaryTree(obj)
else:
t = BinaryTree(obj)
... |
def recursive_sum(arr):
return 0 if not arr else arr[0] + recursive_sum(arr[1:])
|
#invertir una cadena
cadena=input("Introduzca una cadena\n")
print(cadena[::-1])
|
"""DCL - An easy to use diacritic library used for diacritic and accent modification.
This library adds, removes, identifies, and modifies diacritics, with a knuckled down
easy implementation.
DCL currently supports a multitude of diacritics:
* acute
* breve
* caron
* cedilla
* grave
* interpunct
* macron
* ogonek
* ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 20:43:33 2019
To build a model to use volume to predict opening stock prices from closing
+ or -
@author: Faizan
"""
#import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
#make life easier by storing fil lo... |
#lab 3
# for lists just use the + operator to combine two do NOTTTTTT append
# also len() returns the length of a list
# float division = /
# integer division = //
#Function 1
def factorial(n):
#3! = 3 * 2 * 1
answer = 1
for i in range(n):
answer = (i + 1) * answer
return answer
#Function 2
d... |
# sophia zhang
def unmarriedTax(income):
#TO DO: IMPLEMENT FUNCTION
if (income >= 0 and income <= 9700):
taxOwed = .10 * income
elif (income >= 9701 and income <= 39475):
taxOwed = .12 * income
elif (income >= 39476 and income <= 84200):
taxOwed = .22 * income
elif (income >= 842... |
import math
# Task 1: Finish the following four functions
def maxThree(x, y, z):
"""
Returns the maximum of the three parameters
"""
# TODO implement this function
#logically there can only be xyz xzy yxz yzx zxy zyx (greatest to least) or if two variables equal each other just return that
# 1 ... |
#get library for log function
import math
#get user inputs
APR = float(input("What is your APR: %"))
C = float(input("What is the amount owed on the credit card: $"))
p = float(input("What is the monthly payment made: $"))
i = (APR/100)/12
#complete code here
n = (-math.log(1-(i*C/p)))/math.log(i+1)
print("You'll ma... |
def appendicitis(lst):
summation = 0
for i in lst:
summation += int(i)
if summation == 3:
return True
elif len(lst) == 5:
return False
if __name__ == "__main__":
list_values = []
symptoms = ["abdominal pain", "nausea", "vomiting", "fever", "loss of appetite"]
for i ... |
f= lambda x: x**6 - x -1
def sign(x):
# TO DO: Implement this function
if x > 0:
return 1
else:
return -1
def bisect(f, a, b, tau):
c = (a+b)/2
print("{0:.5f} {1:.5f} {2:.5f} {3:.5f} {4:.5f}".format(a, b, c, b-c, f(c)))
if (b-c) <= tau:
return c
elif sign(f(b)) * si... |
import random as rn
def twoMax(xlst):
def mymax(x, y):
if x > y:
return x
else:
return y
# to do: finish the function
if not xlst:
return []
elif (len(xlst[0]) == 1):
return xlst[0]
else:
return [mymax(xlst[0][0], xlst[0][1])] + twoMax... |
def lr(xlst):
# TO DO: IMPLEMENT
longest = 0
tmpcount = 0
while xlst:
if xlst[0] == 1:
tmpcount += 1
if tmpcount > longest:
longest = tmpcount
elif xlst[0] == 0:
if tmpcount > longest:
longest = tmpcount
tmpc... |
from socket import *
import pickle
import sys
if len(sys.argv) != 3:
sys.exit("Format: python3 client.py <ip_address> <port_number>")
serverAddress = sys.argv[1]
serverPort = int(sys.argv[2])
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverAddress, serverPort))
while True:
command = inpu... |
friendsHouse = int(input())
steps = 0
while(friendsHouse):
if(friendsHouse>5):
steps += 1
friendsHouse -= 5
else:
steps += 1
friendsHouse = 0
print(steps)
"""
friendsHouse = int(input())
steps = 0
steps = friendsHouse // 5
steps += 1
print(steps)
""" |
# -*- coding:utf-8 -*-
# Módulo que usa a biblioteca matplotlib para desenhar os gráficos necessários para a estimativa da fase transiente
# (Não é utilizado na versão final)
from math import sin, cos
import matplotlib.pyplot as plt
def plot(list, *args, **kwargs):
plt.plot(xrange(len(list)), list, *args, **kwa... |
#
# @lc app=leetcode id=119 lang=python
#
# [119] Pascal's Triangle II
#
class Solution(object):
# def getRow(self, rowIndex):
# """
# :type rowIndex: int
# :rtype: List[int]
# """
# row = [1]
# for _ in range(rowIndex):
# row = [x + y for x, y in zip([0] ... |
#
# @lc app=leetcode id=445 lang=python
#
# [445] Add Two Numbers II
#
# @lc code=start
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return str(self.val) + (', ' + self.next.__repr__() \
... |
#
# @lc app=leetcode id=160 lang=python
#
# [160] Intersection of Two Linked Lists
#
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type h... |
#
# @lc app=leetcode id=875 lang=python
#
# [875] Koko Eating Bananas
#
# @lc code=start
class Solution(object):
def minEatingSpeed(self, piles, H):
"""
:type piles: List[int]
:type H: int
:rtype: int
"""
def isValid(piles, H, target):
total = 0
... |
#
# @lc app=leetcode id=68 lang=python
#
# [68] Text Justification
#
# @lc code=start
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
ans, cur = [], [] # cur line
cur_len = ... |
#
# @lc app=leetcode id=929 lang=python
#
# [929] Unique Email Addresses
#
# @lc code=start
class Solution(object):
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
ans = set([])
for s in emails:
rs = ''
split = s... |
#
# @lc app=leetcode id=114 lang=python
#
# [114] Flatten Binary Tree to Linked List
#
def listToTree(input):
if not input:
return None
root = TreeNode(int(input[0]))
nodeQueue = [root] # 最后这个包含所有node
front = 0 # to index queue
index = 1 # to index list
while index < len(input):
... |
#
# @lc app=leetcode id=129 lang=python
#
# [129] Sum Root to Leaf Numbers
#
def listToTree(input):
if not input:
return None
root = TreeNode(int(input[0]))
nodeQueue = [root] # 最后这个包含所有node
front = 0 # to index queue
index = 1 # to index list
while index < len(input):
node =... |
#
# @lc app=leetcode id=33 lang=python
#
# [33] Search in Rotated Sorted Array
#
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
lo, hi = 0, l... |
#
# @lc app=leetcode id=126 lang=python
#
# [126] Word Ladder II
#
# @lc code=start
from collections import defaultdict
class Solution(object):
def findLadders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: ... |
#
# @lc app=leetcode id=273 lang=python
#
# [273] Integer to English Words
#
# @lc code=start
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
def three(a):
ans = ''
quo, a = divmod(a, 100)
if quo: ... |
#list demo
"""
shoplist=['apple','mango','carrot','banana']
print("I have",len(shoplist), "items to purchase.")
for item in shoplist:
print(item)
shoplist.append("rice")
print(shoplist)
shoplist.sort()
print(shoplist)
olditem = shoplist[0]
del(shoplist[0])
print(shoplist)
"""
#元组 tuple
"""
zoo = ("wolf",'el... |
def reverse(x):
if x<0:
rev = int(str(x).replace("-","")[::-1])*-1
else:
rev = int(str(x).replace("-", "")[::-1])
if -2147483648 < rev < 2147483648:
return rev
else:
return 0
print(reverse(1345))
|
def lengthOfLongestSubstring(s):
# create dictionary such that you can check if letter has been there
already_here = {}
# create an initial starting point and length to get largest length
start = maxLength = 0
for i, c in enumerate(s):
# if you find that the letter is already there and th... |
import math
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insertionSortList(self, head):
l = ListNode(-math.inf)
while head != None:
self.ins_sort(l, head.val)
... |
def smallestDistancePair(nums,k):
nums.sort()
low = 0
high = nums[-1] - nums[0]
while low < high:
mid = (low + high) // 2
if is_smallest_pair(nums, k, mid):
high = mid
else:
low = mid + 1
return low
def is_smallest_pair(nums, k, mid):
left = 0
... |
def is_palindrome(s: str) -> bool:
s = ''.join(i for i in s if i.isalnum())
s = s.lower()
if s == s[::-1]:
return True
return False
# another solution
# while l < r:
# if s[l] != s[r]:
# print('l is: ', s[l], l)
# print('r is: ', s[r], r)
# re... |
# time"2?:?0"
def latest_time(str):
latest_time = ''
if str[0] == '?':
latest_time += '2'
else:
latest_time += str[0]
if str[1] == '?':
if str[0] == '2':
latest_time += '3'
else:
latest_time += '9'
if str[3] == '?':
latest_time += '... |
import heapq as heap
class Solution:
def kthSmallest(self, root, k):
pq = []
self.explore_node(root, pq)
smallest_k_elements = heap.nsmallest(k, pq)
return smallest_k_elements[-1]
def explore_node(self, node, pq):
if node != None: heap.heappush(pq, node.val)
i... |
def uncommon_words_two_sentences(a, b):
c = (a + ' ' + b).split()
result = []
for i in c:
if c.count(i) == 1:
result.append(i)
return result
A, B = "this apple is sweet", "this apple is sour"
D, F = 'lets try another to_review example', 'the other example is to_review'
print(uncomm... |
import sys
def parse(s):
"""Put a string of 15 characters
into a list if they are x, " ", m, v or o"""
ret = []
for caracter in s:
if caracter == "x" or caracter == " " or\
caracter == "m" or caracter == "v" or\
caracter == "o":
ret.append(caracter)
... |
#create a box with the letter X
'''
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
'''
row = "X X X X X X X X X"
for x in range(9):
print(row)
#make a box
'''
____________________
| ... |
import cv2 as cv
import numpy as np
#读出图像大小和通道
def access_pixels(image):
print(image.shape)
height=image.shape[0]
width=image.shape[1]
channels=image.shape[2]
print("width: %s,height: %s channels : %s"%(width,height,channels))
for row in range (height):
for col in range (width)... |
x = input()
if (x/2) * 2 == x:
print 'True'
else:
print 'False' |
lista=[]
valor=int(input("Ingresa un valor (Presiona 0 para finalizar): "))
while valor!=0:
lista.append(valor)
valor=int(input("Ingresa valor (Presiona 0 para finalizar): "))
print("Tamaño de la lista: ")
print(len(lista)) |
cantidad=0
n=int(input("Cuantos valores ingresara: "))
for f in range(n):
valor=int(input("Ingresa el valor: "))
if valor>=1000:
cantidad= cantidad + 1
print(f"La cantidad de valores ingresados mayores o iguales a 1000 son: {cantidad}") |
lado=int(input("Ingresa la medida del lado del cuadrado: "))
area=lado*lado
print(f"El area del cuadrado es: {area}") |
cantidad=0
x=1
n=int(input("Numero de piezas analizar: "))
while x<=n:
largo=float(input("Ingresa la medida de la barra de acero: "))
if largo>=2.3 and largo<=2.5:
#acumulador
cantidad=cantidad+1
#incrementador
x=x+1
print(f"Cantidad piezas aptas para venta al publico: {canti... |
import tkinter as tk
from tkinter import ttk
class Aplicacion:
def __init__(self):
#Formulario/ventana
self.ventana1=tk.Tk()
#Etiqueta/label
self.label1=tk.Label(self.ventana1, text="Hola y saludos: ")
self.label1.grid(column=0, row=0)
#Caja_texto/en... |
import tkinter as tk
import sys
class Aplicacion:
def __init__(self):
self.ventana1=tk.Tk()
self.ventana1.title("Version sistema")
self.label1=tk.Label(self.ventana1, text="Sistema de Ventas")
self.label1.grid(column=0, row=0)
self.label2=tk.Label(self.ventana1, text="2020")... |
from sys import exit
user_input = input()
operator = [
"+",
"-",
"*",
"/",
"="
] # 연산자 리스트
string_list = [] # 나눈 문자열을 담을 리스트
lop = 0 # 문자열 나누는 것을 도와주는 변수
"""입력 받은 값을 나누는 기능"""
if user_input[-1] not in operator:
user_input += "="
for s in user_input:
if s in operator: # 연산자를 기준으로 문자열을 나... |
def Charlie_PF(N):
if (N < 2):
return 0;
arr = [True] * (N + 1);
prod = 1;
res = 0;
p = 2;
while (p * p <= N):
# If p is prime
if (arr[p] == True):
for i in range(p * 2, N + 1, p):
arr[i] = False;
prod *= p;
if (prod > N):
return res;
res += 1;
p += 1;
ret... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 08:33:55 2020
@author: Juvette
"""
#%%
#Chained Statement
import numpy as np
from numpy.random import randn
#Nested-statements
answer = None
x = randn()
if x > 1 :
answer = "Greater than 1"
elif x >= -1:
answer = "Between -1 and 1"
else:
... |
class Solution:
# @param s, a string
# @return an integer
def minCut(self, s):
# write your code here
def get_is_palindrome(s):
matrix = [[False] * n for i in range(n)]
for i in range(n):
matrix[i][i] = True
for i in range(n-1):
... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
# Divide & Conquer
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
# ... |
class Solution:
"""
@param: s: a string
@return: an integer
"""
def lengthOfLongestSubstring(self, s):
# write your code here
visit = [0] * 256
ans = 0
j = 0
for i in range(len(s)):
while j < len(s) and visit[ord(s[j])] == 0:
... |
# -*- coding: utf-8 -*-
def fib(n):
a, b, i = 1, 1, 2
while i < n:
a, b, i = a + b, a, i + 1
return a
print fib(10) |
"""
Definition for a Directed graph node
class DirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
"""
# 用 template 轻松解决
import Queue
class Solution:
"""
@param: graph: A list of Directed graph node
@param: s: the starting Directed graph node
@param: t: th... |
InNu=input('Please Enter a Number:')
R=int(InNu)%2
print("The Residual is:", R)
if R==0:
print("Your Numer is Even.")
else:
print("Your Number is Odd.")
|
a = 1
b = 2
print(a==b)
print(a!=b)
#print(a<>b)
print(a>b)
print(a<b)
print(2 * a==b) |
NUM1 = float(input("Enter the No: "))
num_sqrt = float(NUM1) ** 0.5
print("The square root of %0.2f is %0.2f" % (NUM1, num_sqrt))
|
def checkio(number):
best_radix = 0
for radix in range(2, 37):
try:
result = int(number, base=radix)
except ValueError:
pass
else:
if result % (radix - 1) == 0:
best_radix = radix
break
return best_radix
... |
'''
Programming Task 2: Hashing
This is our implementation of a hash data structure.
It uses a file as input with the following specs:
# of search keys > 0
search keys (comma separated)
# of buckets
# of records/bucket
'''
class HashTable:
''' A class to hold together all the functions nicely '''... |
from typing import List
class Edge:
node_1 = ""
node_2 = ""
def __init__(self, n_1, n_2):
self.node_1 = n_1
self.node_2 = n_2
def has_nodes(self, n_1, n_2):
if self.node_1 == n_1 and self.node_2 == n_2:
return True
if self.node_1 == n_2 and self.node_2 == ... |
#create file path
import os
import csv
csv_file = os.path.join('..', 'Resources', 'budget_data.csv')
exampleFile = open('./Resources/budget_data.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
#total numnber of months
number_of_months = len(exampleData[1:])
#net total over entire pe... |
import math
def splitTip(total, guests):
try:
(float)(total)
except TypeError:
print("Expected number for total")
else:
if("." in total):
decimal=total.split('.')[1]
if(len(decimal)>2):
raise Exception("Expected only up to 2 decimal places... |
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
for i in range(5):
df = pd.read_csv("../data/train.csv", header=None)
# print("Using word " + str(i))
# df = pd.read_csv("../data/glove_word" + str(i) + "_train.c... |
from collections import defaultdict
n,m = map(int,input().split())
dict_n = defaultdict(list)
counter = 1
for _ in range(n):
dict_n[input()].append(counter)
counter += 1
for _ in range(m):
word = input()
if word in dict_n:
print(" ".join(map(str,dict_n[word])))
else:
print(-1)
|
def solve(s):
name = s[0].upper() + s[1:]
newName = ""
flag = 0
for letter in name:
if flag == 0:
newName += letter
if letter == " ":
flag = 1
else:
if letter.isalnum():
newName += letter.upper()
flag... |
import sys
import random
# read input
line = raw_input("enter number: ")
sw_wins = 0
first_wins = 0
num = int(line)
for i in range (num):
doors = [1,2,3]
# randomly place car
car = random.choice(doors)
my_choice = random.choice(doors)
# randomly open goat door
host_choice = random.choice([x... |
import csv
data = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
def wtite_to_csv(filename, data, delimiter=';'):
with open(filename, 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=delimiter)
writer.writerows(data)
def read_from_csv(filename):
with open(filename, 'r') as csv_file:
reade... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.