text stringlengths 37 1.41M |
|---|
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
if x < 0:
return False
reversal = 0; left = x
while left > 0:
reversal = reversal*10 + left%10
left /= 10
return reversal == x
|
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# Python trick
# 48ms
return str(int(num1) * int(num2))
# https://leetcode.com/discuss/50170/python-understand-solution-without-overflow-with-comment... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} sum
# @return {boolean}
def hasPathSum(self, root, sum):
# Recursive Solution... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify roo... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} p
# @param {TreeNode} q
# @return {boolean}
def isSameTree(self, p, q):
if not p or not q:
... |
#!/usr/bin/python3
def load_input(path):
with open(path, "r") as file:
data = [x.strip() for x in file.readlines()]
return data
def puzzle(right, down):
x, y = (0, 0)
count = 0
for i in data:
x += right
y += down
if x >= len(i):
x -= len(i)
if y ... |
import math
import unittest
def monte_carlo(n):
import random
inside_c=0
outside_c=0
for i in range (1,n+1):
point_x= random.random()
point_y=random.random()
print(point_x,point_y)
d= point_x**2+point_y**2
dist=d**0.5
print(dist)
if dist<=1:
... |
class RouteTrieNode:
def __init__(self, handler: str = None):
self.children = {}
self.handler = handler
def insert(self, path: str, handler: str=None):
self.children[path] = RouteTrieNode(handler)
# Trie structure to store routes and associated handlers
class RouteTrie:
def __init_... |
# ###List Comprehensions
print(list(range(1,11)))
L = []
for i in range(1, 11):
L.append(i * i)
print(L)
# OR
newL = [ x * x for x in range(1, 11) if x % 2 == 0]
print(newL)
S = [m + n for m in 'ABC' for n in 'DEF']
print(S)
import os # 导入os模块
fileName = [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
print(... |
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if intervals is None or len(intervals) < 0:
return []
intervals = sorted(intervals, key = lambda x: x[0])
merged = []
merged.append(intervals[0])
for i in range(1, le... |
#!/usr/bin/env python3
"""
Print out the URLs in a tweet json stream.
"""
from __future__ import print_function
import json
import fileinput
for line in fileinput.input():
tweet = json.loads(line)
for url in tweet["entities"]["urls"]:
if "unshortened_url" in url:
print(url["unshortened_ur... |
#!/usr/bin/env python3
"""
A program to filter tweets that contain links to a web archive. At the moment it
supports archive.org and archive.is, but please add more if you want!
"""
import json
import fileinput
archives = ["archive.is", "web.archive.org", "wayback.archive.org"]
for line in fileinput.input():
tw... |
#!/usr/bin/env python
"""
Prints out the tweet ids and counts of most retweeted.
"""
from __future__ import print_function
import json
import optparse
import fileinput
from collections import defaultdict
def main():
parser = optparse.OptionParser()
options, argv = parser.parse_args()
counts = defaultd... |
#================================================================
# 简单的Numpy程序
#----------------------------------------------------------------
# import numpy as np
# # 数组
# x1d = np.array([4,23,565])
# print(x1d)
# x2d = np.array(((1,2,3),(4,4,4),(7,7,7)))
# print(x2d)
# x = np.array([4,5,6])
# y = np.array([1,2,3]... |
###################################
#thus reverse a string
def rev(s): return s[::-1]
# this asks a question and return the answer.takes whether new line or not
def get_answer(s, newline):
if newline:
print(s)
return (input())
else:
return(input(s))
# this asks a question and return... |
'''
a=["a","b","c","d","100","jjj"]
print(a)
b[0]=a[4]
b[1]=a[3]
b[2]=a[2]
b[3]=a[1]
b[4]=a[0]
'''
def rinurev(a):
size = len(a)
b=[None] *size
for i in range(size):
idx = size-(i+1)
#print (i, idx)
b[i] = a[idx]
return b
'''
c=list(reversed(a))
c.append("rinu")
c.append(a)... |
def nested_sum(L):
sum=0
for i in L1:
if isinstance(i,int):
sum+=i
else:
sum+=nested_sum(i)
return sum
|
#To build an application to classify the patients to be healthy or suffering from
#cardiovascular disease based on the given attributes.
#import numpy as np
"""
HACKATHON
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df=pd.read_excel('D:... |
# FILE: star_wars_adventure_creator.py
# DATE: 2018-11-26
# AUTHOR: Austin Gee
# DESCRIPTION: This is my Final project. It is a menu driven program. Before it
# all starts the program checks to see if the record containing files exist and
# then if they do not the program creates them. Using the menu the user... |
import matplotlib as mpl
class Controller:
def __init__(self, artist):
self.artist = artist
if not isinstance(artist, mpl.backend_bases.Artist):
raise TypeError("artist must be a Matplotlib artist")
self.bindings = {}
event = None
binding = None
while Tru... |
# Create three variables in a single a line and assign different values to them
# and make sure their data types are different. Like one is int, another one is float and the last one is a string
x=10;y=7.5;z="Hello"
print("The integer value is ", x, "and the float value is", y,"and the string value is", z)
|
# Write a program in Python to perform the following operator based task:
# ● Ask user to choose the following option first:
# ○ If User Enter 1 - Addition
# ○ If User Enter 2 - Subtraction
# ○ If User Enter 3 - Division
# ○ If USer Enter 4 - Multiplication
# ○ If User Enter 5 - Average
# ● Ask user to enter the 2 num... |
#!/usr/bin/python
if __name__ == "__main__":
nfood = open("non_food_items_jugaad.txt", "r")
food = open("food_items_jugaad.txt", "r")
count = 0
total = 0
for line in nfood:
count += 1
total += len(line)
avg = float(total)/count
print "nfood avg", avg
count... |
# Design a store using OOP methodologies
from classes import Latlon
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name}, costs ${self.price}"
class Department:
# products will be list of tuples with signature... |
# -*- coding: utf-8 -*-
# EMアルゴリズム(混合正規分布(一変量))
import sys
import os
import numpy as np
import random
import matplotlib.pyplot as plt
import scipy.stats as st
# 正規分布の個数
K = 3
# 正規分布一つあたりのデータ数
P = 500
# 全データ数
N = K*P
# 繰り返し回数
LOOP = 10
# データ,平均,標準偏差
data = []
average = []
sigma = []
#... |
#coin sums
N = 200
S = [1,2,5,10,20,50,100,200]
def change():
change = [1] + [0] * N
for coin in S:
for i in range(coin, N+1):
change[i] += change[i-coin]
return change
if __name__ == '__main__':
print(change()[N])
|
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)+1)):
if n % i == 0:
return False
return True
def find_prime(k):
idx = 0
i = 0
while True:
i = i + 1
if is_prime(i):
idx = idx + 1
if idx ==... |
#Digit fifth powers
# set hand calculated upper limit ~ 6*9^5
UPPER_LIMIT = 356000
def digit_fifth_power_sums():
result = 0
for i in range(2,UPPER_LIMIT):
sum_of_powers = 0
number = str(i)
for n in number:
sum_of_powers += int(n) ** 5
if sum_of_powers == i:
... |
# Quadratic primes
def is_prime(n):
if n < 2:
return False
for i in range(2, int((n**.5)+1)):
if n % i == 0:
return False
return True
def find_consecutive_primes(a,b):
n = 0
while is_prime(abs((n**2) + (a*n) + (b))):
n += 1
return n
if __name__ == '__main__... |
import sqlite3
from datetime import datetime, date
conn = sqlite3.connect('env.db')
c = conn.cursor()
#def main():
# print("Hello DB!")
# createEnv("env9")
# addEnvVM("env9","Kali_07","env_07")
#delEnvVM("env9","Kali_02")
#deleteEnv("env4")
# listEnv("env9")
# listAllEnv()
# conn.close()
def createEnv(env_name):
t... |
def min1(*args):
res = args[0]
for arg in args[1:]:
if arg < res:
res = arg
return res
def min2(first, *rest):
for arg in rest:
if arg < first:
first = arg
return first
def min3(*args):
tmp = list(args)
tmp.sort()
return tmp[0]
print(min1(3,4,1,2))
|
import unittest
from cans import Cola
from customer import Customer
from coins import Quarter, Dime, Nickel, Penny
class TestGetWalletCoin(unittest.TestCase):
"""Tests for Customer's get_wallet_coin method"""
def setUp(self):
self.customer = Customer()
def test_can_return_quarter(self):
... |
# -*- coding: utf-8 -*-
"""
Advent of Code
Day 1 Challenge 1
"""
myfile = open("input.txt","r")
numbers = list()
for number in myfile:
mynum = int(number)
numbers.append(mynum)
#Find 2 numbers that sum to 2020
iter = 1
for num in numbers:
diff = 2020 - num
if diff in numbers:
print(num*... |
"""Module containing base class representing human entity"""
from datetime import datetime
class Human:
"""Base class representing human"""
def __init__(self, **kwargs):
"""Constructor"""
if kwargs is not None:
self._birthdate = datetime.date(datetime.strptime(kwargs.get('birthda... |
"""Module contains class that represent binary tree"""
class BinaryTree:
"""Binary tree representing class"""
def __init__(self, val=None):
"""Constructor"""
self.left = None
self.right = None
self.val = val
def insert(self, val):
"""adds new value to the tree"""
... |
"""Module contains class representing undirected unweighted graph"""
from structures.doubly_linked_list import DoublyLinkedList
class Vertex:
"""Class that represent vertex of graph"""
def __init__(self, name, connected_to=None):
"""Constructor"""
self.connected_to = DoublyLinkedList()
... |
"""Module containing singer entity"""
from main_classes.human import Human
from random import choice
class Singer(Human):
"""Class representing singer"""
_song_list = []
def __init__(self, **kwargs):
"""Constructor"""
if kwargs is not None:
self._salary = float(kwargs.get('sa... |
def main():
numbers = [1, 2, 3, 4, 5]
gen = (value**2 for value in numbers)
for n in gen:
if n == 9:
break
print(n)
square_values = list(gen)
print(square_values)
if __name__ == '__main__':
main()
|
def main():
i = 10
i += 1
print(type(i))
f = 4.5
print(type(f))
i = True
print(type(i))
i = "Hi there"
print("Hi" in i)
print(type(i))
i = 10
j = 10**2
print(i is j)
x = -5
y = 2
print(x // y)
print(x / y)
if __name__ == '__main__':
main()
|
def my_func(a, b):
try:
result = a / b
except ZeroDivisionError as e:
raise ValueError("Argument b can't be 0")
return result
def main():
try:
result = my_func(10, 0)
except ValueError as e:
print(e)
except ZeroDivisionError as e:
print(e)
else:
... |
def func(n):
return n**2
def main():
numbers = [1, 2, 3, 4]
result = list(map(lambda n: n**2, numbers))
print(result)
if __name__ == '__main__':
main()
|
def func(x, y):
return x + y
def runner(f):
print(f(2, 3))
def main():
runner(lambda x, y: x if x < y else y)
f = lambda x, f: f(x*2)
r = f(10,lambda y: 2 * y)
print(r)
ff = lambda x: lambda y: y**x
s = ff(2)
c = ff(3)
print(s(3))
print(s(4))
print(c(3))
print... |
# Stephen Haugland and Shane Snediker
# Artificial Intelligence Spring 2020
# This file contains the agent class defining the little bots that will navigate the maze
import random # Used for randomly seeding DNA
import copy # Used to create deep copy of variables
import math # Used to calculate distance
# ... |
def encrypt(text, key):
#enc=list()
result=""
for i in range(len(text)):
char = text[i]
#uppercase
if(char.isupper()):
result+=chr((ord(char)+(ord(key[i%len(key)])-ord("A"))-65)%26 + 65)
#lowercase
else:
result+=chr((ord(char)+(ord(key[i%len(key)])-ord("a"))-97)%26 + 97)
return result
def main():
t... |
T = input().strip()
while(not T.isdigit()):
T = input().strip()
i = 0
while(i < int(T)):
orgn_str = input().strip()
mid = int(len(orgn_str)/2)
left_str = orgn_str[:mid]
right_str = orgn_str[mid:]
left_str = left_str[::-1]
right_str = right_str[::-1]
strg = left_str + right_str
print(... |
items = [
('Product1', 13),
('Product2', 18),
('Product3', 11)
]
#prices = list(map(lambda item: item[1], items))
prices = [item[1] for item in items]
#filtered = list(filter(lambda item: item[1] >= 12, items))
filtered = [item for item in items if item[1] >= 12]
print(prices)
print(filtered)
|
import csv
# 開啟csv檔案
with open('lesson6/mrt.csv', newline='', encoding='utf-8') as csvfile:
# 讀取csv檔案內容
rows = csv.reader(csvfile)
# 迴圈輸出每一列
for row in rows:
print(row) # list形式
with open('lesson6/mrt.csv', newline='', encoding='utf-8') as csvfile:
rows = csv.DictReader(csvfile)
for ro... |
# 定義一個方程式sequential_add
# 方程式有兩個參數 n1 n2
# 算出n1 - n2之間數字的加總
# 印出結果在terminal
# 注意:不可以使用print
# 例子
# sequential_add(1,10) -> 回傳55
# sequential_add(5,10) -> 回傳45
# sequential_add(10,1000)-> 回傳500455
def sequential_add(n1,n2):
total=0
for i in range(n1,n2+1):
total=total+i
print(total)
sequential_add(1... |
# Python主要有兩種loops形式
# for loops
# while loops
# loops是在給定條件為True的情況下,會持續執行的迴圈
# a loop is used to execute a set of statements as long as a given condition is true
for i in range(5):
print(i)
# String
for c in "python":
print(c)
# list
my_list = ['Alice', 'Tobey']
for name in my_list:
print(name)
# dictionary
m... |
# 請指出以下code錯誤的部分
# 1
# print('Why won't this line of code print')
print("Why won't this line of code print")
# 2
# prnit('This line fails too!')
print('This line fails too!')
# 3
# print "I think I know how to fix this one"
print ("I think I know how to fix this one")
# 4
# input('Please tell me your name: ')
# pr... |
# 定義一個方程式square
# 方程式要輸入一個list
# 算出list裡面數字的平方和
# 印出結果在terminal
# 注意:不可以使用print
# 例子
# [1,2,3] -> 回傳14
# [10,11,12,13,14,15] -> 回傳955
# [10, 100, 1000, 10000]-> 回傳101010100
def square(list):
total=0
for i in list:
total=total+i**2
return total
print(square([1,2,3]))
print(square([10,11,12,13,14,15]... |
def multiply1(num1, num2):
total = num1 * num2
print(total)
return total
def multiply2(num1, num2):
total = num1 * num2
return 'Aloha'
def multiply3(num1, num2):
total = num1 * num2
return total
result = multiply1(5,6)
print(result)
#new_answer = result + 1
#print(new_answer) |
# 使用方程式來畫星星!
# 1. 要求使用者輸入一個數字,存在變數裡
# 2. 定義方程式,將步驟1的數字帶入
# 3. 呼叫方程式,在terminal印出以下圖案
# 例:使用者輸入3
# 在terminal印出(不包括 #)
# *
# **
# ***
# 例:使用者輸入5
# 在terminal印出(不包括 #)
# *
# **
# ***
# ****
# *****
def draw(num):
for i in range(1,num+1):
row=''
for i in range(0,i):
row=row+'*'
pri... |
# Modules(https://docs.python.org/3/tutorial/modules.html)
# 用來儲存程式碼,要使用任何modules只要import便可以使用該module裡的程式碼
# Python Module Index: https://docs.python.org/3/py-modindex.html
# import math
# x = 10.47
# print(math.floor(x))
# print(math.ceil(x))
# print(math.factorial(5))
# ModuleNotFoundError: No module named 'camelc... |
# def multiply(num1, num2=10):
# total = num1 * num2
# return total
# x = 5
# y = 6
# 沒有輸入num2,則會使用default值10
# z = multiply(5)
# print(z)
# mini challenge
# 寫一個算出兩個數的平均的方程式
def avg ( v1, v2 ) :
return (v1+v2)/2
print(avg(10,20)) |
def m(to_move):
return int(to_move / 2)
class pos:
def __init__(self, val, x, y):
self.val = val
self.x = x
self.y = y
all_spots = {}
origin = pos(1, 0, 0)
all_spots[origin.val] = origin
to_move = 2
def move_left(spaces, starting_pos):
start_val = starting_pos.val
start_x ... |
import sys
import random
if len(sys.argv) <= 2:
print "Please enter a filename and a percentage"
exit(1)
filename = sys.argv[1]
percent = int(sys.argv[2])
file = open(filename)
for line in file:
r = random.randint(0,100)
if r < percent:
print line,
|
"""
Intro to Python Lab 1, Task 2
Complete each task in the file for that task. Submit the whole folder
as a zip file or GitHub repo.
Full submission instructions are available on the Lab Preparation page.
"""
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
You will learn more ... |
"""
Consider the following numbers (where n! is factorial(n)):
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
Which will win: 1 / n! or (1! + 2! + 3! + ... + n!)?
Are these numbers going to 0 because of 1/n! or to infinity due to the sum of ... |
l = [1,2,3,4,5,6,7,8,9]
l.append(0)
print(l)
l.insert(4,55)
print(l)
s =[11,22,33]
l.extend(s)
print(l)
print(s)
print(l+s)
print(l)
print(s)
#删除下标删除
print(l.pop(1))
print(l)
print(l.pop())
print(l)
print(l.pop(-3))
#根据内容删除
l.remove(55)
print(l)
#修改列表中数据
l[2]=0
print(l) |
import math
# graph = {'a': {'b': 10, 'c': 3},
# 'b': {'d': 2, 'c': 1},
# 'c': {'b': 4, 'd': 8, 'e': 2},
# 'd': {'e': 7, },
# 'e': {'d': 9}
# }
graph = {'a': {'b': 5, 'c': 1},
'b': {'a': 5, 'c': 2, 'd': 1},
'c': {'a': 1, 'b': 2, 'd': 4, 'e': 8},
... |
#!/usr/bin/env python3
# 列表:list 有序的集合,可以随时添加和删除其中的元素
classmates = ['Michael', 'Bob', 'Tracy']
print("classmates = %s ,len(classmates) = %d" % (classmates, len(classmates)))
# 用索引来访问list中每一个位置的元素, 超出索引范围报错IndexError
print("classmates[0] = ", classmates[0])
# -1 做索引直接获取最后一个元素 依次递推 -2倒数第二个
print("classmates[-1] = ", c... |
# import required packages
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, LSTM, Bidirectional, Conv1D, MaxPooling1D, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras import datasets
from tensorflow.keras.utils import to_categorical
# import tr... |
"""
1. if someBooleanValueIsTrue:
# Do this
else:
# Do that
Note:
The indented line
The lack of a value for the else statement
else is dependent on if
Examples from basic programs:
1.
print("Please enter the password: ")
password = input()
... |
import speech_recognition as sr
import time
from respond import respond
from talk import speak
import os
#The Recognizers for Speech Data
r = sr.Recognizer() #-> General
wake = sr.Recognizer() #-> Wake word
#Clears Screen after each output
def clear():
os.system("cls||clear")
class wakey:
def a... |
subscription = str(input("Please sign up for Programmer's Toolkit Monthly Subsciption from Platinum, Gold, Silver, Bronze or Free Trial:"))
if subscription == "Platinum":
print("Platinum subscription is $60 with a monthly gift of programming books!")
elif subscription == "Gold":
print("Gold subscription is $50... |
import csv
import pandas as pd
def readCSV(readFileName, writeFileName):
df = pd.read_csv(readFileName)
# 初期の前処理
df.dropna() # 欠損値(行)を消すパターン
# df.dropna(axis=1) # 欠損値(列)を消すパターン
for colName in df:
... |
startNum = 13
x = startNum
x = 3
y = x
print(x)
coLen = 0;
while coLen < 1000000:
x = y
coLen = 0
while (x > 2):
if x % 2 == 0:
x = x//2
print(x)
coLen += 1
if x % 2 != 0:
x = 3 * x + 1
print(x)
coLen += 1
y += 1
p... |
class GameItem:
def __init__(self, display_name=None):
self.unique_id = self.generate_id()
if not display_name:
self.display_name = str(self.unique_id)
def generate_id(self):
"""
TODO: mechanism for ensuring every generated ID is unique/psuedorandom
:return:
... |
from sys import argv
script, first, third = argv
print("Here is your script", script)
print("Here is your first variable", first)
second = input("Please enter a second variable: ")
print(f"Here is the input variable {second}, and here is your last variable: {third}")
|
"""
"""
import collections
__all__ = ['ConcreteSet']
class ConcreteSet(collections.MutableSet):
"""
Set-class, used by Union and Optional.
Holds types, subject to set-theoretic operations.
Will eventually be used by Intersection and Not.
"""
def __init__(self, *data):
self.data = set... |
"__main__: generate the list from sys.argv"
import sys
from .assassin import generate
def main(length : int = 3):
"print a textual representation of a cycle of given length (default 3)"
for assassin, victime, action in generate(limit=length):
print(f'{assassin = }')
print(f'{victime = }')
... |
import sys
import time
def get_primos() :
i = 1
j = 1
while j < 1001 :
if is_primo(i) :
print("Primo numero ", j," : ",i)
j += 1
i += 1
return True
def is_primo(n) :
for i in range(3,n//2,2) :
if n%i == 0 :
return False
return True
... |
def merge_sort(list_):
len_ = len(list_)
if len_ <= 1:
return
mid = len_ // 2
first = list_[mid:]
second = list_[:mid]
merge_sort(first)
merge_sort(second)
i, j, k = 0, 0, 0
while j < len(first) and k < len(second):
if first[j] and second[k]:
if first[j] <... |
# For random number generation
# https://cryptography.io/en/latest/random-numbers/
import os
# Library for hashBackend (openssl)
# https://cryptography.io/en/latest/hazmat/backends/
from cryptography.hazmat.backends import openssl
# Lirary for Hash functions like SHA-2 family, SHA-3 family, Blake2, and MD5
# https://cr... |
from abc import ABC, abstractmethod
from Elevator.wrappers import printlog
# abc can not be instantiated itself, subclasses need to implement all abstract methods (override) but can provide
# custom logic via super()
# abc is a form of interface checking more strict than hasattr(), we get error upon instantiation
cla... |
class enum(object):
"""Just plug in a dict to give a mapping of strings to other values."""
def __init__(self, enumdict=None):
self.enum_dict = enumdict
def run(self, val):
if self.enum_dict:
self.enum_dict.get(val, None)
|
#Man-Shaped Pinata
import sys
men = {
1:"""
-----
| |
|
|
|
|
|
----------
""",
2:"""
-----
| |
| O
|
|
|
|
----------
""",
3:"""
-----
| |
| O
| |
|
|
|
----------
""",
4:"""
-----
| |
| O
| /|
|
|
|
----------
""",
5:"""
-----
| |
| O
| /|\\
| |
|
|
------... |
class Node(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.left = None
self.right = None
self.size = 1
class Binery_Tree(object):
def __init__(self):
self.node = None
self.size = 0
def insert(self, tree, node):
if tree.node... |
'''1.在一个二维数组中(每个一维数组的长度相同),
每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
'''
#二分查找
def Find(target, array):
# write code here
for i in array:
for x in i:
if target == x:
return True
else:
continue
return F... |
# Luyện tập cách xây dựng hàm, sử dụng hàm, các lệnh vẽ, tùy chỉnh bút vẽ trong thư viện turtle.
import turtle
t = turtle.Turtle()
def home_draw(x,y):
t.pencolor("blue")
for j in range(2):
for k in range(1,3):
t.fillcolor("pink")
t.begin_fill()
t.penup()
... |
#Hiển thị ngày trong tuần
# 1: Monday
# 2: Tuesday
# 3: Wednesday
# 4: Thursday
# 5: Friday
# 6: Saturday
# 7: Sunday
Number = int(input("Vui lòng nhập 1 số trong khoảng từ (1~7):"))
if(Number == 0 or Number > 7):
print("error, out of range")
elif(Number==1):
print("Monday")
elif(Number==2):
print("Tuesday"... |
def take_input():
books_no, lib_no, total_days = map(int, input().split())
book_scores = list(map(int, input().split()))
list_of_lib = []
def sortonscore(val):
return book_scores[val]
for i in range(lib_no):
lib_info = tuple(map(int,input().split()))
lib_books = list(map(in... |
# The python interpreter goes through your code line by line, and tries to make
# sense of it. If it sees a line prefixed with # it ignores it. This is called
# a COMMENT, and is just used to provide more information to other humans
# reading your code.
# However, if it sees a line that is not a comment, it will try t... |
# This is the skeleton for exercise-2. The goal is to change the fizzbuzz()
# function so that it returns the string "fizz", if the number passed as an
# argument is divisible by 3, "buzz" if it is divisible by 5, and "fizzbuzz"
# if it is divisible by 3 and 5. You can use the predefined
# computer_remainder() function... |
import numpy as np
# --------------------------------------------------
# Example 1
# load a colour image and put it into a 3D numpy array
# -------------------------------------------------
# Example 2
# assume that arr is an n-dimensional numpy array
# apply a function to all elements of the array
# parr = np.log(... |
l = list()
while s:= input():
l.append(s)
prev = set()
for i, s in enumerate(l):
post = set()
for j in range(i+1, len(l)):
post |= set(l[j])
if not (set(s) & (prev | post)):
print(s)
prev |= set(s) |
a, b, c, = eval(input())
if a>0 and b>0 and c>0 and a+b>c and b+c>a and c+a>b :
print("Possible")
else:
print("Impossible")
|
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("spark-demo").getOrCreate()
"""# DataFrame
## Read the CSV file into a DataFrame
"""
bankProspectsDF = spark.read.csv("bank_prospects.csv",header=True)
"""## Remove the record with unknow value in country column"""
bankProspectsDF1 = bankPro... |
class Employee():
def __init__(self,name,mname,salary):
self.name = name
self.mname = mname
self.salary = salary
emp=Employee("John","Moses",34566)
print("Employees deatils:\n")
print("name:{}, manager name:{}, sal:{}".format(emp.name,emp.mname,emp.salary))
|
lenght = input("请输入长:")
width = input("请输入宽:")
lenght_num = int (lenght)
width_num = int(width)
i = 1
j = 1
while i<=width_num:
print("*"*lenght_num)
i=i+1
|
class Cat:
#属性
def __init__(self,new_name,new_age):
self.name = new_name
self.age = new_age
#方法
def eat(self):
print("吃")
def drink(self):
print("喝")
def introduce(self):
print("%s的年龄是%d"%(self.name,self.age))
#创建一个对象
tom = Cat("汤姆",40)
tom.eat()
... |
ticket = 1 #1表示有车票
knifeLength = 50#cm
if ticket == 1:
print("通过车票检查,进入车站,接下来安检")
if knifeLength <=10:
print("通过了安检,进入到候车亭")
else:
print("安检没通过")
else:
print("没买票,不能进站")
|
class Node:
def __init__(self, val):
self.ainz = None
self.ooal = None
self.gown = val
class Tree:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add(self, val):
if(self.root == None):
self.root =... |
for x in "Python":
print(x)
for x in range(5):
print(x)
for x in range(0, 10, 2):
print(x)
|
import sys
with open(sys.argv[1], "r") as f:
data = f.read().split("\n")
numbers = list(map(int, data))
def insum(num, numbers):
for i, x in enumerate(numbers):
for y in numbers[:i] + numbers[i+1:]:
if x + y == num: return True
return False
def part1(nums):
for i, e i... |
# Background
class Background(object):
def __init__(self, constant=0.0, prefactor=0.0, alpha=-2.0, prefactor2=0.0, alpha2=-1.5):
''' This is a background of type:
constant + prefactor*q^alpha + prefactor2*q^alpha2
Nothing special, but since it is so common an object is left for book... |
'''
lab7 while loop
'''
#3.1
i=0
while i<=5:
if i !=3:
print(i)
i= i+1
#3.2
i= 1
result =1
while i<=5:
result = result *i
i = i+1
print(result)
#3.3
i= 1
result = 0
while i<=5:
result = result +i
i = i+1
print(result)
#3.4
i= 3
result =1
while i<=8:
result ... |
import sys
import heapq
def fractional_knapsack(capacity, cost_and_volumes):
order = [(-c / v, v) for c, v in cost_and_volumes]
heapq.heapify(order)
total_cost = 0
while order and capacity:
c_per_v, v = heapq.heappop(order)
can_take = min(v, capacity)
total_cost -= c_per_v * c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.