text stringlengths 37 1.41M |
|---|
pickle 标准模块。
它可以在一个文件中储存任何Python对象,之后又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
在pythony 3.0 已经移除了 cPickle 模块,可以使用 pickle 模块代替。
################## 示例 #####################
import pickle as p # 这里使用 as 简称,方便更改模块时只需改一行代码
# import cPickle as p # Python 2.x 有这个模块(比pickle快1000倍)
# 将会把资料保存在这个文件里面
shoplistfi... |
# !/usr/bin/python
# -*-coding: utf-8-*-
numero = 31
salir = False
while salir == False :
if (numero % 7 == 0) or (numero % 7 == 1):
J1 = "Ti"
if (numero % 7 == 2) or (numero % 7 == 3) or (numero % 7 == 6):
J1 = "Pi"
if (numero % 7 == 4) or (numero % 7 == 5):
J1 = "Pa"
if (numero % 5 == 0) or (numero % 5... |
def main():
num = int(raw_input())
notmirror = ["Q","E","R","P","S","D","F","G","J","K","L","Z","C","B","N"]
for i in range(0,num):
error = 0
word = raw_input()
rvs = word[::-1]
for l in notmirror:
if l in word:
error = 1
if rvs == word and error == 0:
print ("YES")
else:
pri... |
"""
Write a class TempTracker with these methods:
insert()—records a new temperature
get_max()—returns the highest temp we've seen so far
get_min()—returns the lowest temp we've seen so far
get_mean()—returns the mean ↴ of all temps we've seen so far
get_mode()—returns a mode ↴ of all temps we've seen so far
Optimize ... |
#!/usr/bin/env python3
import sys
donor_db = [('Eddie Vedder', [10000.00, 20000.00, 4500.00]),
('Chris Cornell', [100.00, 500.00]),
('Kurt Cobain', [25.00]),
('Dave Matthews', [100000.00, 50000.00, 125000.00]),
('Dave Grohl', [50.00])]
prompt = '\n'.join(('Welcome to ... |
# 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
#
# 示例 1:
#
# 输入: s = "abcabcbb"
# 输出: 3
# 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
#
# 示例 2:
#
# 输入: s = "bbbbb"
# 输出: 1
# 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
#
# 示例 3:
#
# 输入: s = "pwwkew"
# 输出: 3
# 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
# 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
#
# 示例 4... |
# 875. 爱吃香蕉的珂珂
# 珂珂喜欢吃香蕉。这里有 N 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 H 小时后回来。
# 珂珂可以决定她吃香蕉的速度 K (单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 K 根。如果这堆香蕉少于 K 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。
# 珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。
# 返回她可以在 H 小时内吃掉所有香蕉的最小速度 K(K 为整数)。
#
# 示例 1:
# 输入: piles = [3,6,7,11], H = 8
# 输出: 4
#
# 示例 2:
# 输入: piles = [30,11... |
# 49. 字母异位词分组
# 难度 中等
# 给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
# 字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。
#
# 示例 1:
# 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
# 输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
#
# 示例 2:
# 输入: strs = [""]
# 输出: [[""]]
#
# 示例 3:
# 输入: strs = ["a"]
# 输出: [["a"]]
# ... |
# 105. 从前序与中序遍历序列构造二叉树
# 给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
# 关键点在于理解前序遍历和中序遍历结果的特点。参考 https://labuladong.gitee.io/algo/2/18/23/
# 下面的代码在递归时使用了值传递,这样函数更加简洁,可以改为传递引用加 index 位置以提升效率
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val... |
# 450. 删除二叉搜索树中的节点
# 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
# 一般来说,删除节点可分为两个步骤:
# 首先找到需要删除的节点;
# 如果找到了,删除它。
# 关键点在于删除一个节点后,找到它的右子树中最小的一个节点来代替它。
# 会有一些细节需要处理,一个不容易出错的原理就是拆分成独立的小函数
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None... |
# 503. 下一个更大元素 II
# 给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
# 使用单调栈,循环数组的技巧是将数组复制一份接到原来的数组后面,优化的技巧是索引值取余。
class Solution:
def nextGreaterElements(self, nums: list[int]) -> list[int]:
n = len(nums)
m = [None for _ in... |
# 5. 最长回文子串
# 给你一个字符串 s,找到 s 中最长的回文子串。
# 示例 1:
# 输入:s = "babad"
# 输出:"bab"
# 解释:"aba" 同样是符合题意的答案。
#
# 示例 2:
# 输入:s = "cbbd"
# 输出:"bb"
#
# 示例 3:
# 输入:s = "a"
# 输出:"a"
#
# 示例 4:
# 输入:s = "ac"
# 输出:"a"
# 技巧是以每一个字符为中心,向两边拓展,看最大能组成多大的回文字串。
# 但回文字符串长度可能为偶数,所以算法思路为:
# for i in range(0, len(s)):
# 找到以 s[i] 为中心的回文字符串,
... |
# 496. 下一个更大元素 I
# nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
# 给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
# 对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
# 返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述... |
# 96. 不同的二叉搜索树
# 给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。
# 使用递归的方法
# 随便选择一个数作为 root,则总的不同 BST 的个数,就是左边不同 BST 的个数,乘以右边不同 BST 的个数。
# 由于 n 个节点的值为 1 到 n,可以想象从小到大逐个选择节点作为 root,则左子树肯定由小于它的节点组成,右子树由大于它的节点组成。
# 由于存在重复计算,可以优化加上缓存
class Solution:
def __init__(self) -> None:
self.memo = {}... |
# 1584. 连接所有点的最小费用
# 给你一个points 数组,表示 2D 平面上的一些点,其中 points[i] = [xi, yi] 。
# 连接点 [xi, yi] 和点 [xj, yj] 的费用为它们之间的 曼哈顿距离 :|xi - xj| + |yi - yj| ,其中 |val| 表示 val 的绝对值。
# 请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有 一条简单路径时,才认为所有点都已连接。
# 抽象为计算图的最小生成树 MST
class Solution:
def minCostConnectPoints(self, points: list[list[int]]) -> int... |
# 297. 二叉树的序列化与反序列化
# 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
# 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
# 提示: 输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
# Your Codec object will be ... |
# coding:utf-8
# author: Fengzhijin
# time: 2017.11.22
# ==================================
'''
运用K-means解决FashionMNIST数据识别问题
1.loadMNIST() - 数据读取函数
2.Distance() - 欧氏距离计算函数
3.randCent() - 质心初始化函数
4.Kmeans() - Kmeans算法实现函数
'''
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import nu... |
class Student:
def __init__(self):
self.name = 'Obama'
self.age = 30
self.marks = 900
def talk(self):
print('Hi my name is ', self.name)
print('Age is', self.age)
print('Marks are', self.marks)
#create an instance to Student class
s1= Student()
s1.tal... |
class Teacher:
def setid(self, id):
self.id = id
def getid(self):
return self.id
def setname(self, name):
self.name = name
def getname(self):
return self.name
t = Teacher()
t.setid(10)
t.setname('Vaib')
print('Your id is ', t.getid())
print('Your ... |
import numpy as np
#Iris is a sample datasets provides by scikit learn
from sklearn.datasets import load_iris
from sklearn import tree
#IMPORT DATASET
#Load the iris data set
iris = load_iris()
#index of variables to be deleted for testing
test_idx = [0,50,100]
# print(iris.feature_names)
# print(iris.targ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 9/20/18 17:24
# @Author : Kaiwen Xue
# @File : US02.py
# @Software: PyCharm
# Birth before marriage
from datetime import datetime
import re
def birt_before_marr(indi_list, fam_list):
for people in indi_list:
if people['SPOUSE'] != 'NONE':
... |
# Author: Mayank Bhardwaj
# Start date: 18 may 2018
# Last modified date: 26 May 2018
# Version 1.0 (please update the version while implementing the code changes)
# -------------------------------Version 1.0------------------------------------
# This code for analysing the number of occurrences for each character... |
string = 'Python is fun'
string_upper = str.upper(string) # Fill in the blank
print(string_upper)
|
file = input('Enter the file name: ')
if file == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
quit()
else:
try:
with open(file, 'r') as file1:
for line in file1:
line = line.rstrip()
print(line.upper())
except:
print('... |
largest = None
while True:
numbers = input('Enter a number: ')
if numbers == 'done' :
break
try:
number_int = int(numbers)
if smallest is None:
smallest = number_int
elif number_int < smallest:
smallest = number_int
elif largest is None:
... |
from scipy.spatial import distance_matrix
import matplotlib.pyplot as plt
import numpy as np
def get_graph_mat(n=10, size=1):
""" Throws n nodes uniformly at random on a square, and build a (fully connected) graph.
Returns the (N, 2) coordinates matrix, and the (N, N) matrix containing pairwise euclidean... |
def compareDataUnits(value1, value2):
if value1 > value2:
totalUnits = value1 - value2
totalUnitsPercentage = abs(((totalUnits/value1)*100))
print('Total Decrease:', totalUnitsPercentage,'%')
elif value1 < value2:
totalUnits = value1 - value2
totalUnitsPercentage... |
import numpy as np
def containsZero(vector):
print('indexes of "0" elements:', np.where(vector == 0))
def containsInf(vector):
print('indexes of "inf" elements', np.where(vector == np.inf))
print('indexes of "-inf" elements', np.where(vector == -np.inf))
def compare(x, y):
print("first vector/matrix:... |
#get_parity.py
def check_parity():
x=int(input('Введите число '))
if x%2==0:
return 'Число четное'
else:
return 'Число нечетное'
print (check_parity())
|
# Import the required packages
import socket
import time
import json
import datetime
class peers:
# Contructor
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.next = None
self.flag = False
self.ip = None
# Initial state of the peer... |
def f(x, y):
"""
:type y: list[int]
:type x: str
:rtype: int
"""
y.append(int(x))
try:
# this should error since list has no 'x' member
y.x()
except:
pass
return int(x)
print(f("4", [1,2,3]))
|
### Visualizing Motor Vehicle Accidents in NYC using a Streamlit Web App ###
# Import required python library
import streamlit as st # Streamlit for deploying webapp
import numpy as np
import pandas as pd
import pydeck as pdk # PyDeck for for creating beautiful maps
import plotly.expres... |
#Bike Share project for 3 cities in USA
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'Chicago': 'chicago.csv',
'New York City': 'new_york_city.csv',
'Washington': 'washington.csv' }
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str)... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 19:30:34 2020
@author: Geetu
"""
"""
In this one I added a score and made it say the score.
After asking a question, it deletes it from the list
Note: The list,not the dict
It also has an option of "quit". If you say quit it says"Have a nice day."
"Your scor... |
from math import sqrt
n = int(input("Kaç adet sayı girmek istersiniz ?"))
list= []
carpım = 1
for i in range(n):
sayi = int(input("Sayı giriniz :"))
list.append(sayi)
carpım *= sayi
geometrik_ortalama = sqrt(carpım)
print("Geometrik Ortalama = ", round(geometrik_ortalama, 3))
|
import numpy as np
import random
class QLearning:
def __init__(self, domain, alpha, gamma, epsilon):
# sets the domain instance, and all relevant parameters for each algorithm
# (e.g. learning rate, epsilon, etc.).
self.domain = domain
self.alpha = alpha
self.gamma = gamma
... |
'''Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"... |
'''Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has ex... |
'''Given two version numbers, version1 and version2, compare them.
Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision ... |
'''Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the s... |
# Write a program that counts
# how many times it has been run.
# store the data (persist) in a txt file.
filename = "count.txt"
def readNumber():
with open(filename) as f:
number = int(f.read())
return number
# test it
num = readNumber()
print (num) |
# This program asks for a name input, then prints hello + name
# Author: Betty Attwood
#option one in hash to allow option 2 to run
#name=input("Enter your name: ")
#print('Hello ' + name + '\nNice to meet you')
#same option with formatting
name = input("Enter your name:")
print('Hello {}\nNice to meet you' .format(n... |
# This tuple stores the months of the year
# and another stores the summer months.
# The program prints out the summer months one at a time.
months = (
"January","February",
"March", "April", "May", "June",
"July", "August", "September",
"October", "November", "December"
)
summer = months [4:7]
# t... |
# This program floors a number
# Flooring Rounds a number down to the nearest integer
# Author: Betty Attwood
import math
numberToFloor = float(input("Enter a float number:"))
flooredNumber = math.floor(numberToFloor)
print('{} floored is {} '.format(numberToFloor, flooredNumber))
|
# This program asks the user to guess a number
# and provides feedback of whether
# the number is higher or lower than the guess
# Author: Betty Attwood
import random
numberToGuess = random.randint(0, 100)
#Ref https://pynative.com/python-random-randrange/#:~:text=For%20example%2C%20random.,number%20from%20the%20inc... |
# This program gives the absolute value of a number
# Author: Betty Attwood
# Note number did not specify int or float
# based on the output I assume float is required.
number = float(input("Enter a number:"))
absoluteValue = abs(number)
print('The absolute value of {} is {} '.format(number, absoluteValue)) |
# indexing and searching 26th Feb
#search for word, value error if not found
# 0 is first position
x = 'happy birthday'
x.index('birthday')
x.index('hello')
# search for word, no value error
x.find('hello')
x.find('happy')
x.find(' ')
# search - outputs first result for multiples
y = 'happy happy'
y.i... |
# This is a summary of the 7 data types in Python
# useful tip for these notes: comment a block using
# ctrl {with} / {with} +
# Text Type:
# str
# Numeric Types:
# int, float, complex
# Sequence Types:
# list, tuple, range
# Mapping Type:
# dict
# Set Types:
# set, frozenset
# Boolean Type:
#... |
sexo = raw_input("Indique su sexo: ")
edad = input("Indique su edad: ")
if edad >= 18 :
print "Eres mayor de edad, puedes emborracharte!!!"
else:
print "Lo siento con " , edad , " no puedes emborracharte"
|
#14. Longest Common Prefix --leetcode
"""
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : AntiOrder.py
# @Author: 投笔从容
# @Date : 2018/5/23
# @Desc : 求一个数组的逆序对
# -*- coding:utf-8 -*-
class AntiOrder:
def __mergeSort(self, arr, l, r):
count = 0
if l >= r:
return count
mid = int((l + r) / 2)
count1 = se... |
"""
Date:Jan. 22 2021
Author:Andrew Lin
Description: An S-Expression Calculator that performs the add and multiply
operator on natural numbers.
"""
import sys
def get_parsed_list(string):
"""
get_parsed_list(string) Consumes a string and returns the string
in a parsed list
Examples:
... |
def square_root_1():
c=10
i=0
g=0
for j in range(0,c+1):
if(j*j>c and g==0):
g=j-1
while (abs(g*g-c)>0.0001):
g+=0.00001
i=i+1
print("%d:g=%.5f"%(i,g))
square_root_1() |
x=int(input())
r=0;
Rs=[];
while(x != 0):
r=x%2
x=x//2
Rs=[r]+Rs
for i in range(0,len(Rs)):
print(Rs[i],end='')
#进制计算取结果时,最后一个求余的结果是最高位
'''
r=x%2,%求余,//整数除
x=x//2
'''
|
#!/usr/bin/env python
# coding: utf8
import re
countBits = [bin(x).count("1") for x in range(1 << 13)]
def calcSubsetScore(bitmask):
score = 0
for x in range(13):
if bitmask & (1 << x):
score += allenPriority[x]
return score
allenPriority = [26, 82, 82, 82, 82, 82, 82, 50, 50, 50, 5... |
'''
This is a training material for Python 3
Functions
How to define a function
How to call a function
Pass by Reference
Types of arguments in function (Required, Keyword, Default, Variable length)
Scope of variables (Global and Local)
'''
# How to define a function
# Function blocks... |
'''
numerate() in Python
A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task.
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enu... |
import deck
class Player:
""" Represents one player taking part in the card game """
def __init__(self, id: int):
""" Initialize a player with an identifier
Args:
id: An integer that identifies this player
"""
self._ident = id
self._hand = []
def get... |
#!/usr/bin/env python
"""mapper.py"""
import sys
# input comes from STDIN (standard input)
def clean_up_list(word_list):
clean_word_list = []
for word in word_list:
symbols = "\'!@#$%^&*()+_{<>}:\"<>?.,;[]-=1234567890"
for i in range(0, len(symbols)):
word = word.replace(symbols[i... |
def collatz(number):
if number%2 == 0:
print(number/2)
return number/2
else:
print(number*3 + 1)
return(number*3 + 1)
while True:
try:
intInput = int(input('Please enter an integer: '))
break
except ValueError:
print('That is not an integer!')
whi... |
list1 = [1, 2, 3, 4, 5, 6]
list2 = [1, 3, 5, 7, 9, 11]
list1_as_set = set(list1)
intersection = list1_as_set.intersection(list2)
intersection_as_list = list(intersection)
print(intersection_as_list)
|
import tkinter as tk
# Define the data points
data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]
root = tk.Tk()
root.title("Bar Graph")
c_width = 400 # Define it's width
c_height = 350 # Define it's height
c = tk.Canvas(root, width=c_width, height=c_height, bg='white')
c.pack()
# The variables below size the bar graph
y... |
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
ERROR = 'Error.TLabel'
SUCCESS = 'Success.TLabel'
def __init__(self):
super().__init__()
self.title('Change Password')
self.geometry("300x130")
self.password_var = tk.StringVar()
self.confirm_password_... |
import re
_hostname_re = re.compile('(?!-)[A-Z\d-]{1,63}(?<!-)$', re.IGNORECASE)
def valid_address(address):
"""
Determines whether the specified address string is valid.
"""
if not address:
return False
components = str(address).split(':')
if len(components) > 2 or not valid_hostna... |
#grade=int(input().strip())
n = int(input())
grades = []
for _ in range(n):
grades_item = int(input())
grades.append(grades_item)
for i in range(len(grades)):
diff=5-(grades[i]%5)
if(diff<3):
newgrade=grades[i]+diff
else:
newgrade=grades[i]
if (newgrade>=40):
grades[i]=n... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
43. Multiply Strings
https://leetcode.com/problems/multiply-strings/
"""
class Solution:
def multiply(self, num1: str, num2: str) -> str:
l = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, "0": 0}
def strToInt(a: str):
... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
82. Remove Duplicates from Sorted List II
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
解题思路:
创建新的链表,尾插
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = ... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
65. Valid Number
https://leetcode.com/problems/valid-number/
"""
class Solution:
def isNumber(self, s: str) -> bool:
s = s.strip() # 去掉两端的空白符
if not s:
return False
else:
# 去掉开头的正负号
if s[0] in ['+', '-']:
... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
20. Valid Parentheses
https://leetcode.com/problems/valid-parentheses/
"""
class Solution:
def isValid(self, s: str) -> bool:
stack = list()
dict = {'(': ')', '[': ']', '{': '}'}
for c in s:
if c in dict.keys():
st... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
75. Sort Colors
https://leetcode.com/problems/sort-colors/
解题思路:
荷兰三色旗问题
三个指针(p0, p2 和curr)来分别追踪0的最右边界、2的最左边界和当前考虑的元素
沿着数组移动 curr 指针,若nums[curr] = 0,则将其与 nums[p0]互换,p0向右移;若 nums[curr] = 2 ,则与 nums[p2]互换,p2向左移
"""
from typing import List
class Solution:
def sortColor... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
70. Climbing Stairs
https://leetcode.com/problems/climbing-stairs/
解题思路:
最后一步可能跨了一级台阶,也可能跨了两级台阶,所以 当x > 1 时 f(x) = f(x-1) + f(x-2),x表示当前台阶层数
"""
class Solution:
def climbStairs(self, n: int) -> int:
# second_in_front 前二级台阶的到达路径有几种
# first_in_front 前一... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
25. Reverse Nodes in k-Group
https://leetcode.com/problems/reverse-nodes-in-k-group/submissions/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(sel... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
44. Wildcard Matching
https://leetcode.com/problems/wildcard-matching/
"""
class Solution:
def isMatch(self, s: str, p: str) -> bool:
s_len, p_len = len(s), len(p)
s_idx = p_idx = 0
# 用于记录回溯位置
star_idx = s_tmp_idx = -1
while ... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
10. Regular Expression Matching
https://leetcode.com/problems/regular-expression-matching/
1、"."表示任意字符
2、"*"表示任意个*前面的字符(aaaaaa = a*, aaaab != a*)
"""
class Solution:
def isMatch(self, s: str, p: str) -> bool:
lens = len(s)
lenp = len(p)
dp =... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
59. Spiral Matrix II
https://leetcode.com/problems/spiral-matrix-ii/
解题思路:
生成 n * n 的空矩阵,然后模拟整个向内环绕的填入过程
参考:
https://leetcode-cn.com/problems/spiral-matrix-ii/solution/spiral-matrix-ii-mo-ni-fa-she-ding-bian-jie-qing-x/
"""
from typing import List
class Solution:
de... |
from collections import Counter
def get_domain(email_address):
"""split on '@' and return the last piece"""
#lower() 轉為小寫
#.split("@")[-1] 取@後面的資料
return email_address.lower().split("@")[-1]
with open('email.txt', 'r') as f:
domain_counts = Counter(get_domain(line.strip())
for line in f
if "@" in line)
#資料理有'... |
# Write a Python program to convert seconds to day, hour, minutes and seconds.
given = int(input("Enter number of seconds: "))
days = given / (3600 * 24)
days = int(days)
remainder = given % (3600 * 24)
hours = remainder / (60 * 60)
hours = int(hours)
remainder = remainder % (60 * 60)
minutes = remainder / 60
minut... |
# Write a Python program to get the least common multiple (LCM) of two positive integers.
from math import lcm
int1 = int(input("Enter an integer. (Negative integers will be converted to positive anyway.): "))
int2 = int(input("Enter another integer. (Negative integers will be converted to positive anyway: "))
int1 ... |
# Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string
# already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3,
# leave it unchanged. Go to the editor
# Sample String : 'abc'
# Expected Result : 'abcing'
# Sa... |
# Write a Python program to print without newline or space.
print("Some Text", end="")
print("More Text", end="") |
# Write a Python program that will accept the base and height of a triangle and compute the area.
base = float(input("Enter the length of the base of the triangle: "))
height = float(input("Enter the length of the height of the triangle: "))
area = base * height / 2
print(area) |
# Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times
# of their sum.
given1 = int(input("Enter a number: "))
given2 = int(input("Enter a number: "))
given3 = int(input("Enter a number: "))
sum = given1 + given2 + given3
if given1 == given2 == given3:
... |
# Write a Python program to remove the nth index character from a nonempty string. DONE
input_string = str(input('Enter a string: '))
def remove_nth(given, n):
final = given[:n] + given[n+1:]
print(final)
remove_nth(input_string, 4) |
# Write a Python program to concatenate all elements in a list into a string and return it.
def concatinate(x):
output = ""
for i in x:
output = output + str(i)
print(output)
concatinate([12, "us", 2, 3, 4]) |
# Write a program to print the calendar of a given month and year.
import calendar
month = str(input('INPUT -- Enter a 3 letter abbreviation for a month: '))
year = str(input('INPUT -- Enter a 4 digit year: '))
month = month.lower()
def convert_month(mmm):
abbrev_month = ['jan', 'feb', 'mar', 'apr', 'may', 'jun... |
# Write a program to accept a filename from the user and print the extension of that.
filename = input('Enter a filename with a .extension: ')
filename_list = filename.split('.')
print(filename_list)
print(filename_list[1]) |
# Write a Python program to print out a set containing all the colors from color_list_1 which are not present in
# color_list_2. Go to the editor
# Test Data :
# color_list_1 = set(["White", "Black", "Red"])
# color_list_2 = set(["Red", "Green"])
# Expected Output :
# {'Black', 'White'}
color_list_1 = set(["White", "B... |
# Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the
# string length is less than 2, return instead of the empty string. Go to the editor
# Sample String : 'w3resource'
# Expected Result : 'w3ce'
# Sample String : 'w3'
# Expected Result : 'w3w3'
# Sample String... |
# Write a Python program to generate a random color hex, a random alphabetical string, random value between two
# integers (inclusive) and a random multiple of 7 between 0 and 70. Use random.randint()
import random
import string
random_color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
max_length = 255
random_stri... |
# Write a function that takes a number as a parameter and check if the number is prime or not. DONE
def find_prime(num):
print(num)
divisible = False
for x in range(2, (num-1)):
if num % x == 0:
divisible = True
print('Number is NOT PRIME!')
break
else:... |
# Write a Python program to display the current date and time.
# Sample Output :
# Current date and time :
# 2014-07-05 14:34:14
import datetime
print('Current date and time:\n', datetime.datetime.now().strftime("%x %X"))
# DONE |
# -*- coding: utf-8 -*-
"""Python generators examples.
A generator is an implementation using the lazy evaluation strategy.
"""
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
if __name__ == '__main__':
from os import getcwd
from os import sys
sys.path.append(getcwd())
import os
from MOAL.helpers... |
# -*- coding: utf-8 -*-
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
if __name__ == '__main__':
from os import getcwd
from os import sys
sys.path.append(getcwd())
from random import randrange as rr
from MOAL.helpers.display import Section
from MOAL.helpers.display import prnt
from MOAL.helpers.di... |
# -*- coding: utf-8 -*-
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
if __name__ == '__main__':
from os import getcwd
from os import sys
sys.path.append(getcwd())
DEBUG = True if __name__ == '__main__' else False
# Surprising (and bad) --------------------------------------------------------
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 17:04:53 2019
@author: sensenliu
"""
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param intervals: interval list.
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: nums: an integer array
@return: the first node of linked lis... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
class Solution:
"""
@param nums: A list of integer
@return: An integer, maximum coins
"""
def maxCoins(self, nums):
if not nums:
return 0
balloons = [1] + nums + [1]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 21:22:24 2019
@author: sensenliu
"""
class ConnectingGraph:
"""
@param: n: An integer
"""
def __init__(self, n):
self.root_array = [i for i in range(n+1)]
def find(self, n):
# node number fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of link... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param airplanes: An interval array
@return: Count of airplanes are in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.