text stringlengths 37 1.41M |
|---|
class Solution:
def preprocess(self, s):
ret = "^#"
for ch in s:
ret += ch
ret += "#"
ret += '?'
return ret
def postprocess(self, s, center, d):
ret = s[center - d:center + d + 1]
ret = ret.split('#')
return ''.join(ret)
def ... |
"""
Author: Raguram R D
Python 3.7 - Spyder
"""
from itertools import permutations as perm #to create the permutations
import operator as op #to work with operators
line = '40 1 4 3 51' #Sample input
number_check = 42 #The number that need to evaluated
ip_split = line.split(' ')
list_op = [op.add... |
score= {
"수학":90,
"국어" : 87,
"한국지리": 92
}
print(round(sum(score.values()) / len(score)),2)
scores = {
"a학생" : {
"수학": 80,
"영어": 72,
"한국지리":42
},
"b학생" : {
"수학" : 22,
"영어" : 32,
"한국지리" : 53
}
}
for key,value in scores.items():
print... |
from pathlib import Path
import PyPDF2
import docx
#Access the PDF File you want to censor
file = open('Haferkorn.pdf', 'rb')
pdf = PyPDF2.PdfFileReader(file)
#Change this line if you want to censor information NOT on the first page
first_page = pdf.getPage(0)
#Store your Text
page_text=first_page.extractText()
#Add... |
def sum1(numbs):
s = 0
for i in range(len(numbs)):
s += numbs[i]
print(s)
return s
def sum2(numbs):
s = 0
for x in numbs:
s += x
return s
def is_in(x,list1): #用于检查在一个表里是否存在某个元素
for y in list1:
if y == x:
return True
return False
def... |
def char_count(s,dic):
for c in s:
if not c.isalpha():
continue
c = c.lower()
dic[c] = dic.get(c,0) + 1
d1 = {}
char_count("Python is a programming language", d1)
print(d1)
char_count("想去爬山?去紫金山还是老山",d1)
print(d1["山"]) |
#!/usr/bin/python
#-*-coding:utf-8-*-
def printMax(x,y):
'''Prints the maxnum of two number'''
x=int(x);
y=int(y);
if (x>y):
print(x,"is maxnum");
else:
print(y,"is maxnum");
printMax(3,5);
print printMax.__doc__; #doc是属性,不是方法,所以不能加() |
#linear search time
from time import perf_counter
import random
def linear_search(l,n):
for number in l:
if number==n:
return (True)
else:
pass
return (False)
size=[10**i for i in range(4,8)]
t=[]
for x in size:
l=[random.randint(0,x) for i in range(x)]
n=random.randint(0,x)
t1=perf_counter()
linear_s... |
# coding=utf-8
# 数组中只出现一次的数字
# 在一个整数数组中,除了一个数之外,其他的数出现的次数都是两次,求出现一次的数
# 异或运算的特点:任何一个数字和自己做异或运算的结果都是0,任何数字和0运算的结果都是本身
list = [2, 2, 3, 9, 3, 6, 6]
def findOne(list):
res = 0
for i in list:
res ^= i
return res
res = findOne(list)
print(res) |
def pulling(b, r):
while r > 0:
if r >= 100:
r -= 100
b -= 100
print ("give 100")
elif r >= 50:
r -= 50
b -= 50
print ("give 50")
elif r >= 10:
r -= 10
b -= 10
print ("giv... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
stack=[]
while True:
while root:
stack.... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# Logic of this problem is that lCA only are not empty when there is one target in its children .
# If the left and right are both no... |
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.p=[]
def push(self, x: int) -> None:
curMin = self.getMin()
if curMin==None or x<curMin:
curMin=x
self.p.append((x,curMin))
... |
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
dic={5:0,10:0}
for i in range(len(bills)):
if bills[i]==5:
dic[5]+=1
elif bills[i]==10:
if dic[5]>0:
dic[10]+=1
dic[5]-=1
... |
class Solution:
# XOR rules:
# 3^3=0 0^3=0
# XOR obeys Exchange law so 0^3^1^3=0^3^3^1=1
def singleNumber(self, nums: List[int]) -> int:
res=0
for x in nums:
res=res^x
return res
|
class Solution:
# Using visited to maintain the status of the nodes
# If the node is visited and status is 1, means this node has no ring.
# This works better than using Boolean, because boolean could only maintain the status visited or not in this time.
def canFinish(self, numCourses: int, prerequisite... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# BFS
def invertTree(self, root: TreeNode) -> TreeNode:
queue=collections.deque()
if root:
queue.append(r... |
# 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]]:
res=[]
queue=collections.deque([root])
while queue:
... |
class Solution(object):
def missingNumber(self, nums):
Set=set()
for item in nums:
Set.add(item)
for i in range(len(nums)+1):
if i not in Set:
return i
# Mathematics is great!
def missingNumber1(self, nums):
"""
:type nu... |
# -*- coding: utf-8 -*-
#
# This is part of events extractions
#
# Created by Alejandro Molina
# october 2020
#
# This project is licensed under CC License - see the LICENSE file for details.
# Copyright (c) 2020 Alejandro Molina Villegas
#
# clustering data by vector distances
import numpy as np
from sklearn.clust... |
# Let's work with real numbers i.e. 1.5 2.7 etc
i = 1
j = 2
k = 3
x = k / j
print("x is ", x)
i = x / 3
print("i is ", i)
x = int( k / j ) # Because I want the whole part, I explicitly converted to int
print("x converted to integer is ", x)
x = int (1.6) # Supposed to be rounded to 2, has whole part 1
print("x from 1.6... |
#! /usr/bin/env python
# -*- coding:utf-8
# Using Large Data from Stanford(Sentiment140), Predicting sentiments using a deep neural network with tensorflow.
# Special thanks: Harisson@pythonprogramming.net
'''
File name: sentiment_predict_large_nn.py
Author: chimney37
Date created: 11/23/2017
Python Ve... |
'''
This code will download daily pricing data, on a minutely basis, to our SP500 directory.
'''
import csv
import pickle
import pandas as pd
import pandas_datareader.data as web
from matplotlib import style
# ------------------------------------------------------------------------------------------------------------... |
# define Python user-defined exceptions
class Error(Exception):
'''Base class for other exceptions'''
pass
class ValueTooSmallError(Error):
'''Raised when the input value is too small'''
pass
class ValueTooLargeError(Error):
'''Raised when the input value is too large'''
pass
# Our main pr... |
import sys
from cell import Cell
class Sudoku:
# initialize a sudoku puzzle based on a 2D array which is passed in
def __init__(self,puzzle=None):
# if no preexisting puzzle is passed in (console case)
if puzzle is None:
print "puzzle not provided"
self.puzzle = self.co... |
radius = float(input("Enter the Radius: "))
const_PI = 3.14
area = const_PI * (radius*radius)
print("The area of the circle is: ",area)
|
from pyspark import SparkConf, SparkContext
spark_conf = SparkConf().setMaster("local").setAppName("friends-by-age")
sc = SparkContext(conf=spark_conf)
spark_file = sc.textFile("dataset/friends-100k/fake-friends-100k.data")
# getting age and total friends from each line
friends = spark_file.map(lambda x: (int(x.split... |
# on function call, print out message asking user to select drink or snack
# Then, print appropriate choices depending on user input
# check if payment is enough
# check if choice is correct
# if so, return change, choice
def vendingMachine(money):
drinkList = ["Sprite","Coke","Water"]
... |
"""
This problem was asked by Google.
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
For example, given the following Node class
class Node:
def __init__(self, val, left... |
from sys import argv, exit
import csv
if len(argv) != 3:
print("Usage: database.csv sequence.txt")
exit(1)
Database = open(argv[1], "r") # Initalizing variable which reads second command line argument
DNAsequence = open(argv[2], "r") # Initalizing variable which reads third c... |
import hashlib
# b = bitestring, strips metadata away
# ending with '.encode()' does the same thing
key = b'str'
my_string = 'this is a normal string. Nothing to see here'
for i in range(10):
hashed = hashlib.sha256(key).hexdigest()
print(hashed)
for i in range(10):
hashed = hash(key)
print(hashed %... |
def twobit(colorstring):
'''w = white, s = silver, g = grey, b = black'''
return int('0b'+colorstring.replace('w', '11').replace('s', '10').replace('g', '01').replace('b', '00'), 2)
while 1:
try:
print(twobit(input('s?\n> ')))
except:
pass |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 15:27:27 2018
@author: adkarumo
"""
import pandas as pd # imports pandas library
from sklearn import tree # imports tree from sklearn
import os
# Titanic: Machine Learning from Disaster
# Kaggle link: https://www.kaggle.com/c/titanic/data
# Read titanic train data u... |
#!/usr/bin/env python
import game
import gameio
r = 4 ;
l = 4 ;
boardsList = game.allocBoard(r, l);
mineBoard = boardsList[0];
statusBoard = boardsList[1];
mineBoard[0][0] = -1;
mineBoard[0][3] = -1;
print("initial board: ")
gameio.displayBoard(mineBoard, statusBoard);
game.uncoverLoc(mineBoard, statusBoard, 2, 2... |
suits = 'CDHS'
ranks = '23456789TJQKA'
from abc import ABCMeta, abstractmethod
class Card(metaclass=ABCMeta):
"""Abstact class for playing cards
"""
def __init__(self, rank_suit):
if len(rank_suit) == 2:
self.rank, self.suit = rank_suit
elif len(rank_suit) == 3:
... |
import turtle
import random
turtle.tracer(1,0)
SIZE_X=800
SIZE_Y=600
turtle.setup(SIZE_X, SIZE_Y)
turtle.penup()
SQUARE_SIZE = 20
START_LENGTH = 7
pos_list = []
stamp_list = []
food_pos = []
food_stamps = []
snake = turtle.clone()
snake.shape("circle")
snake.color("blue")
turtle.hideturtle()
for i in range(START_LE... |
def search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
print("Enter array elements separated by space")
arr = [int(x) for x in input().split()]
print("Enter element to search")
k=int(input())
pos=search(arr, k)
if pos==-1:
print("Element Not fo... |
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
print("Enter array elements separated by space")
arr = [int(x) for x in input().split()]
insertionSort(arr)
print(*arr)
|
# This program is used to print a list of words in random order
# This demonstrates the use of lists
import random
title = "welcome to the random word chooser!"
print("\t\t" + title.title() + "\n")
words = ["hi", "bye", "arrivederci", "python"]
size = len(words)
while size:
print(words.pop(random.randint(0, si... |
def decimal_to_bin(dec):
return bin(int(dec))
def decimal_to_hexdec(dec):
return hex(int(dec))
def bin_to_decimal(binary):
return int(str(binary), 2)
def bin_to_hexdec(binary):
return hex(int(str(binary), 2))
def hex_to_bin(hex):
return bin(int(hex, 16))
def hex_to_decimal(hex):
return int(hex, 16)
de... |
#Roman characters for units
units = ['', 'I', 'II', 'III', 'IV','V','VI','VII','VIII','IX']
#Roman characters for tens
tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
#Roman characters for hundreds
hundreds = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC','CM']
#Roman characters for thousa... |
# -*- coding: utf-8 -*-
"""Supplementary numerical/statistical functions
Short functions used to extract functionality. Function names meant to
be self-explanatory and document the purpose of calculation they contain.
"""
import numpy as np
from pandas import notna
from scipy.stats import zscore, pearsonr
def clean... |
[x1] =[int(i) for i in raw_input().split()]
def divisores(numero):
divisores = []
for x in range(numero):
if x != 0:
if x1%x == 0:
divisores.append(x)
return divisores
def somaDivisores(divisores):
soma = 0
for x in divisores:
soma += x
return soma
if somaDivisores(divisores(x1)) == x1:
print 'e... |
import zipfile
import os
import re
import string
class Descompactador(object):
def descompactarZips(self, arquivosCompactados, destino):
for file in arquivosCompactados:
#separa somente a matricula para criar uma pasta com os codigos fontes dentro
dirAluno = string.split(file, '_')
dirAluno = string.spl... |
'''
This script standardizes the data for machine learning.
'''
import numpy as np
def datasplitter(x):
'''
Split data and classes for a dataset.
inputs:
x = The data containing features with the last column being the class
outputs:
data = The feature data
class = The class ... |
def validate_string(s, variable_name=""):
assert isinstance(s, str), "{} not a string".format(variable_name)
assert s != "", "{} is empty".format(variable_name)
return s
def validate_int(i, variable_name=""):
assert isinstance(i, int), "{} not an int".format(variable_name)
return i
def validate_do... |
"""
题目:将一个列表的数据复制到另一个列表中。
"""
while True:
list=input("请输入列表找那个的元素,中间用,隔开:").split(",")
list_new=list[:]
print(list_new) |
#
# @lc app=leetcode.cn id=113 lang=python3
#
# [113] 路径总和 II
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Tr... |
#
# @lc app=leetcode.cn id=208 lang=python3
#
# [208] 实现 Trie (前缀树)
#
# @lc code=start
class Node(object):
def __init__(self, val, end=False) -> None:
self.val = val
self.end = end
self.children = [None for _ in range(26)]
class Trie:
def __init__(self):
"""
Initialize ... |
#
# @lc app=leetcode.cn id=98 lang=python3
#
# [98] 验证二叉搜索树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
re... |
import numpy as np
from PIL import Image
from utils import *
import argparse
from scipy import fftpack
#https://github.com/ghallak/jpeg-python
#https://stackoverflow.com/questions/7762948/how-to-convert-an-rgb-image-to-numpy-array
def main():
fichier = open("data.txt", "w")
#Partie 0 : ouverture de l'image
parser ... |
# A demonstration of how image processing will be used for project
import numpy as np
import cv2
from matplotlib import image as image
import easygui
import tkinter as tk
import os.path
from numpy import expand_dims
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_a... |
"""
Subarray Sum Equals K
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the rang... |
"""
Number of Good Leaf Nodes Pairs
Given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input:... |
"""
Move Zeroes
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]
Note:
-You must do this in-place without making a copy of the array.
-Minimize the total number of operations.
"""
cl... |
"""
Construct Binary Tree from Preorder and Inorder Traversal
Solution
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
... |
"""
Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution:
"""
Brute force would be checkin... |
"""
Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
... |
"""
91. Decode Ways
Medium
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as... |
"""
234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solut... |
"""
Uncrossed Lines
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:
A[i] == B[j];
The line we draw does not intersect any other connecting (non-horizontal) line.
Note that ... |
"""
Group Anagrams
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
"""
class Solution:
def groupAnagrams(self,... |
"""
3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
... |
"""
Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:... |
"""
Power of Three
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
"""
class Solution:
"""
3 ^ (log 3 MaxInt) = 3 ^ 19.56 = 3 ^ 19 = 1162261467
Now Python does not have MaxInt anymore. But this is a good
approach.
"""
... |
"""
Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cann... |
"""
Graph can be given in many ways. Here just taking the adjencency
list as the input.
The adjecency list will change depending on whether the graph is
directed or undirected. The code remains the same.
Uses of BFS:
- Finding shortest path**
- Solving rubik's cube
- Finding all paths
"""
class BreadthFirstSearch:
"""... |
"""
Single Element in a Sorted Array
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,10,11,... |
#compound intrest A = P(1 + R/100) t
principal=float(input("Enter Proncipal Amount "))
rate=float(input("Enter Annual Rate "))
time= float(input("Enter time in years "))
final_amount= float (principal*(1+((rate/100)*time)))
print(final_amount) |
import numpy as np
from scipy.optimize import minimize
from scipy.io import loadmat
from math import sqrt
import time
import pickle
selected_features = []
def initializeWeights(n_in, n_out):
"""
# initializeWeights return the random weights for Neural Network given the
# number of node in the in... |
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
def is_outlier(points, thresh=3.5):
"""
Returns a boolean array with True if points are outliers and False
otherwise.
Parameters:
-----------
points : An numobservations by numdimensions array of observations... |
# Implementação da Trie, adaptada do site
# https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
# com adaptações para funcionar com endereços IPs e inclusão de ajustes propostos no artigo referência.
from typing import Tuple, Any
# Estrutura básica ... |
"""
Created on Thu May 30 13:47:52 2019
用執行緒做出賽馬遊戲,
模擬10匹馬(1-10號)。
距離為1000公尺,
每匹馬每0.5秒會跑80+20*R公尺,
R為0-1的亂數。
當有一匹馬跑了1000公尺後則為列出各匹馬的名次和跑的總距離
"""
import time
import threading
import random
run_result=[0]*10
#print(ping_result)
num_horses=10 #馬數目
# Horse 類別,負責處理資料
class Horse(threading.Thread):
def __init__(self, n... |
class Car:
# Реализовать класс машины Car, у которого есть поля: марка и модель автомобиля
# Поля должны задаваться через конструктор
def __init__(self, model, brand):
self.model = model
self.brand = brand
def __str__(self):
return self.model + ' ' + self.brand
class Garage:
... |
#tutorial - https://www.youtube.com/watch?v=y1RnweT17v0
class ListNode(object):
""" Definition for singly-linked list."""
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def sortList(self, head):
"""
identify mid
"""
... |
from fractions import Fraction
from math import ceil
from collections import OrderedDict
def center_text(txt, width):
assert (width >= len(txt)), 'Field width must be at least the length of the text'
num_spaces = width - len(txt)
return (' ' * (ceil(num_spaces / 2))) + txt + (' ' * (num_spaces // 2))
cl... |
#Lemmatizing and wordnet
from nltk.stem import WordNetLemmatizer
lemmatizer=WordNetLemmatizer()
#Find practical meanings for words. Spanish?
print(lemmatizer.lemmatize("cats"))
print(lemmatizer.lemmatize("cacti"))
print(lemmatizer.lemmatize("geese"))
print(lemmatizer.lemmatize("rocks"))
print(lemmatizer.lemmatize("p... |
# Github: Shantanugupta1118
# DAY 57 of DAY 100
# Palindrome String - InterviewBit
# https://www.interviewbit.com/old/problems/palindrome-string/
class Solution:
def isPalindrome(self, A):
lst=[]
for i in A.lower():
if ord(i)>=97 and ord(i)<=102 or (ord(i)>=48 and ord(i)<=57):
... |
# Github: Shantanugupta1118
# DAY 69 of DAY 100
# Disjoint Union - GFG
# https://practice.geeksforgeeks.org/problems/disjoint-set-union-find/1#
class Solution:
def find(self, parent, x):
if x == parent[x-1]:
return x
parent[x-1] = self.find(parent, parent[x-1])
return parent[x-... |
# Github: Shantanugupta1118
# DAY 87 of DAY 100
import time
from functools import lru_cache
# --------------- NAIVE THEORY BASED ---------------
'''
class Solution:
def check_factor(self, x, y):
while x%y==0:
x = x// y
return x
def isUgly(self, x):
x = self.check_fact... |
# Github: Shantanugupta1118
# DAY 55 of DAY 100
# Concentric Square Grid - InterviewBit
# https://www.interviewbit.com/problems/prettyprint/
class Solution:
def concentric_grid(self, n):
grid = n*2 - 1
dp = [[0 for x in range(grid)] for x in range(grid)]
for i in range(grid):
f... |
import ccxt
import datetime
from abc import ABCMeta, abstractmethod
class AbstractAccount(object):
"""
AbstractAccount is an abstract class providing an interface for all
subsequent (inherited) accounts.
The goal of a (derived) Account object is to provide information about
the current balance fo... |
#!/usr/bin/env python3
import gzip
import csv
import shelve
import os
forward = {}
backward = {}
def load_wikipedia_titles(file):
if file[-3:] == '.gz':
input = gzip.open(file, mode='rt', encoding='utf-8', newline='')
else:
input = open(file, 'r', encoding='utf-8', newline='')
with inpu... |
#!/usr/bin/env python
#####################################################################################################################################################
# This script accepts the csv file at run time and generate a new CSV file that only includes properties sold for less than the average price / foo... |
"""
[ 함수 ]
반복적인 구문을 만들어 함수로 선언하여 간단하게 호출만 하고자 한다
def 함수명(매개변수):
수행할 문장들
"""
# (0) 인자도 리턴값도 없는 함수
# def func(): # 함수 정의부
# print('inside func')
#
# func()
# print(func()) # 리턴값이 없으면 None을 반환한다
# (1) 리턴값이 2개인 함수
# print('(1)-----------------------------------------')
# def func(arg1, arg2)... |
import random
#import math
"""x=math.radians(30)
y=math.radians(60)
z=math.sin(x)/math.cos(y)
print(z)
a=math.radians(90)
z=math.isfinite(math.tan(a))
print(z)"""
for i in range(10):
t=[5,6,7,8]
a=[1,4,2,5]
#z=random.randint(5,10)
#print(z)
z1=random.choices(t,a)
print(z1)
|
import csv
import Payment
def __printDictionary(donors):
for key, value in donors.items():
print(key)
for payment in value:
print(payment.toString())
print("\n\n")
# given an array of payments from a donor, the function
# then calculates the total amount of payments the donor
#... |
list_a = [21, 23, 25, 27, 29]
print(list_a)
print(list_a[2])
print(list_a[1:4])
print(list_a[-1])
#Ubah Element List
list_a[3] = 20
print(list_a[3])
list_a[3:4] = 22, 24
print(list_a[3:5])
#Tambah ELement List
list_b = list_a[0:2]
print(list_b)
list_b.append(26)
print(list_b)
list_b.extend([30, 3... |
#!/usr/bin/python3
import psycopg2
DBNAME = "news"
'''
Method that gets popular articles of all time from news database
'''
def get_popular_articles():
db = psycopg2.connect(database=DBNAME)
file = open("test.txt", "w")
cursor = db.cursor()
cursor.execute('''
select a.slug, count(l.ip)
from l... |
"""
Solution to Project Euler problem by Joseph Jude
Webpage: http://tech.jjude.com/euler
Git Repo: https://github.com/jjude/euler
Problem 004: Find the largest palindrome made from the product of two 3-digit numbers.
WIL: reversing a string
"""
answer = 0
for i in xrange(999, 100, -1):
for j in xrange(i, 100, -... |
"""
修改属性的值:
1.直接通过实例进行修改
2.通过方法进行设置
3.通过方法进行递增
"""
#1.直接通过实例进行修改
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make=make
self.model=model
self.year=year
self.odometer_reading=0#添加一个属性,初始化为0,不需要在实例中给予实参
def get_descriptive_name(self):
"""返回整洁的描述性信息"""... |
"""
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引
序列,同时列出数据和数据下标 -- (索引,值),一般用在 for 循环当中。
enumerate(iterable, [start=0])
iterable -- 可迭代对象。
start -- 下标起始位置。
"""
my_list = ['Wuminfeng', '男', 19]
print(list(enumerate(my_list)))
print("----------------------------")
#用于for循环中
numbers = ['one', 'two', 'three']
f... |
magicians=['anthony','alice','carolina']
for magician in magicians:
print(magician.title()+", that was a great trick!")
print("I can't wait to see your next trick.\n")
print("Thank you, everyone.That was a great magic show!")
|
#http://www.runoob.com/python3/python3-inputoutput.html
"""
从文件中读取数据
1. 读取整个文件
2. 逐行读取
3. 创建一个包含文件各行内容的列表
"""
#1. 读取整个文件
with open('pi_digits.txt') as file_object:#默认为只读'r'
contents = file_object.read()# f.read(size) 从当前位置读取size个字符
print(contents.rstrip())
#read()到达文件末尾时返回一个空字符串,显示出来就是一个空行
"""
要以任何方式使用文件,都得... |
#使用函数range(),从第一个参数值开始数,到第二个参数值停止(不包含第二个参数值)
for number in range(1,3):
print(number)
print("--------------------------------")
#使用函数range()创建数字列表,将函数range()生成的数字作为函数list()的参数
numbers=list(range(1,11))
print(numbers)
print("--------------------------------")
#函数range()第三个参数指定递增数
numbers=list(range(2,11,2))
print(number... |
from functools import reduce
"""
Python使用lambda来创建匿名函数。
lambda的主体是一个表达式,仅仅能在lambda表达式中封装有限的逻辑进去。
lambda函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。
"""
f = lambda x: x+1
print(f(1))
print("--------------------------------")
#lambda面试题
li = [lambda : x for x in range(10)]
#help(li) li是一个列表
#help(li[0]) li中的元素是函数
for i in... |
def words_count(filename):
"""计算文本中某个单词出现的次数"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("Sorry, the file " + filename + " doesn't exist.")
'''
pass
'''
else:
print(contents.lower().count('the'))
words_count('alice.txt')
|
import unittest
from city_functions import city_functions
class NamesTestCase(unittest.TestCase):
"""测试city_functions"""
def test_city_country(self):
"""测试城市-国家格式"""
city_country = city_functions('santiago','chile')
self.assertEqual(city_country,'Santiago, Chile')
#断言方法assertEqual来自于TestCase
def tes... |
#关键字and
age_0=22
age_1=18
print(age_0 >=21 and age_1>=21)
age_1=23
print(age_0 >=21 and age_1>=21)
print("------------------------")
#关键字or
age_0=22
age_1=18
print(age_0 >=21 or age_1>=21)
age_0=18
print(age_0 >=21 or age_1>=21)
|
#数到20
for number in range(1,21):
print(number)
print("-------------------------------")
'''#创建列表,包含数字,使用函数list()
numbers=list(range(1,1000001))
print(numbers)
print("-------------------------------")
#函数min()/max()/sum()
print(min(numbers))
print(max(numbers))
print(sum(numbers))
print("-------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.