text stringlengths 37 1.41M |
|---|
'''
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
You may ass... |
'''
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
'''
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
prev = cur = 0
rem = { 'M': 1000, 'D': 500, 'C': 10... |
'''
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)
The solution set must not contain duplicate triplets.
For example, gi... |
class Solution:
def __init__(self):
self.trie = {}
def addWords(self, dict_words):
for word in dict_words:
node = self.trie
for w in word:
if w not in node:
node[w] = {}
node = node[w]
node['_end_'] = True
... |
'''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
... |
'''
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
Credits:
Special thanks to @ifanchu for ... |
'''
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide Company Tags Bloomberg
Hide Tags Math
Hide Similar Problems (H) Number of Digit One
Difficulty: Ea... |
'''
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
'''
# Definition for a binary tree node.
class TreeNode(object):... |
'''
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*... |
'''
'''
class TicTacToe(object):
def __init__(self):
self.board = [['' for j in range(3)] for i in range(3)]
self.num_of_used_cell = 9
def print_board(self):
for i in range(3):
for j in range(3):
print "-" if not self.board[i][j] else self.board[i][j]... |
import math
def primeSquare(n):
isprimes = primes(n+1)
if isprimes[n]:
return n ** 2
s = 0
for i in range(1, n+1):
if isprimes[i]:
s += (i ** 2)
else:
s += i
return s
def primes(n):
isprimes = [True] * max(n, 2)
isprimes[0], isprimes[1] = ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, n):
self.val = x
self.next = n
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
self.reverse_list_helper(head)
return head
def reverse_list_helper(self, head):
... |
'''
Created on Dec 22, 2012
@author: dharadarji
1) Given: Binary tree, (no parent link)
Goal: Find first common ancestor of 2 nodes in binary tree
TODO O ??
2) Given: Binary tree WITH parent link
Goal: same
Algo: Follow parent link of p and q, make it visited,
if following parent , you encounter parent is visited,... |
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
'''
class Solution:
# @param num, a list of integers
# @return an integer
def maj... |
def recurringTask(firstDate, k, daysOfTheWeek, n):
tasks = []
date, month, year = map(int, firstDate.split('/'))
t = 1
tasks.append(firstDate)
weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
firstDay = getDay(firstDate)
print "First... |
'''
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
'''
class Solution(object):
def maxProfit(self, prices):
"""
... |
#!/usr/bin/python
class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
result = set()
num_perm = self.find_permutation(num, result)
print num_perm
return max(result, key=lambda num: int(num))
def find_permutation(self, list_num, num_perm):
if len(list_nu... |
'''
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11... |
'''
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an i... |
'''
Given a column title as appear in an Excel sheet, return its
corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
'''
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
pos = {}
pos['A'] = 1
for i in range (1, 27):
... |
'''
Contains Duplicate
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
'''
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {boolean}
... |
'''
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only consta... |
'''
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog",... |
'''
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its ve... |
'''
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycl... |
'''
Given a pattern and a string str, find if str 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 substring in str.
Examples:
pattern = "abab", str = "redblueredblue" should return true.
pattern = "aaaa", str = "asdasdasdasd" should ... |
num=int(input())
factorial=1
if(num>0):
for i in range(1,num+1):
factorial=factorial*i
print(factorial)
elif(num==0):
print("1")
else:
print("sorry")
|
def gcd(x,y):
if(y==0):
return x
else:
return gcd(y,x%y)
x,y=map(int,input().split())
GCD=gcd(x,y)
print(GCD)
|
class Polynomial:
def __init__(self, coefficients):
self.coefficients = coefficients
def evaluate(self, x):
total = 0
for c in self.coefficients:
total += self.coefficients[c] * x ** c
return total
|
for i in range(5):
print('Das ist der ' , i, ' te durchlauf')
print('\n')
for i in range(1, 10, 2):
print('Das ist der ' , i, ' te durchlauf')
print('\n')
for i in range(1, 10, 2):
print('Das ist der ' , i, ' te durchlauf')
print('\n')
bin_pleite = False
kontostand = 10
while bin_pleite == False:
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from helper import *
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
x, y = regression_data()
print(x.shape)
#print(x)
x = x.reshape(-1, 1) # muss gemacht werden da sklearn und keras jedes ... |
#
# There are two option for return type "image" and "print".
# If you select "image" it will show result as image .
# Otherwise result will be shown as coordinates.
# Use http://www.mazegenerator.net/ for maze generating purposes
# Because at this stage this script recognizes maze generated from link above.... |
#Author: Stephen Pryor
#Date: September 22, 2012
import math
def linearRegression(X, Y):
XY=[X[i]*Y[i] for i in range(len(X))]
XX=[x*x for x in X]
sigmaX = sum(X)
sigmaY = sum(Y)
sigmaXY = sum(XY)
sigmaXX = sum(XX)
N=float(len(X))
slope = (N*sigmaXY-(sigmaX*sigmaY))/(N*sigmaXX-sigmaX*sigmaX)
i... |
"""
Hello there
My name is Maira Iantas and this is my first time using python
I will start this documentation today and I will check in the future the
the progress that I've made, let's check it out
"""
# This project was coded using VS Core
# Python 3.9.5
print("Hello World!")
print("Python --version to get the ve... |
from .position import Position
class MacGyver:
""" I'm the player. """
def __init__(self, maze):
""" Initialize position and bag. """
self.maze = maze
self.paths = maze.paths
self.mg_pos = self.maze.start_pos
self.item1_pos = self.maze.item1_pos
self.item2_pos ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
import tkinter
win=tkinter.Tk()
win.title("zhl")
win.geometry("400x400+200+0")
"""
供用户通过拖拽指示器改变变量的值,可以水平,也可以竖直的,比如 音量控制的scale
"""
# orient=tkinter.HORIZONTAL 控制水平或竖直orient=tkinter.VERTICAL
##length: 水平时,表示宽度, 竖直时,表示高度;
##tickinterval 选择值将会为改制的倍数
scale1=t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
"""
两个线程同时工作,一个存钱,一个取钱
可能会导致数据异常
解决的思路:是加锁
"""
import threading
num=0
lock=threading.Lock()
def run(n):
global num
for i in range(1000000):
##加锁的方法1
lock.acquire()
##如果临界区的代码执行异常时,会导致无法解锁,会进入死锁状态,所以我们一般需要使用异常处理的方式,来确保一定会执行解... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
##需求:写一个购物小程序
# 1.用户启动时先输入工资
# 1.用户启动程序后,打印商品列表;
# 2.允许用户选择购买商品
# 3.允许用户不断的购买各种商品;
# 4.购买时,检测余额是否足够,如果够,直接扣款,否则打印“余额不足”
# 5.允许用户主动退出程序,退出是打印已够列表;
salary=input("请输入工资:")
if salary.isdigit():
salary=int(salary)
else:
exit("invalid data type")
welcome_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
#
class Mytype(type):
def __init__(self,*args,**kwargs):
print("init")
super(Mytype,self).__init__(*args,**kwargs)
def __call__(cls, *args, **kwargs):
print("call")
return super(Mytype,cls).__call__(*args,**kwargs)
de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
"""
使用队列实现生产者和消费者
"""
import threading,queue
import time,random
##生产者
def producer(i,q):
while True:
num=random.randint(0,1000)
q.put(num)
print("生产者%d---生产了%d数据放入了队列"%(i,num))
time.sleep(3)
#任务结束
q.task_done()
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
import threading,time
cond=threading.Condition() ##线程条件变量
# def run1():
# for i in range(0,10,2):
# print(threading.current_thread().name,i)
# time.sleep(1)
#
#
# def run2():
# for i in range(1,10,2):
# print(threading.curre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:
"""
multiprocessing 是一个跨平台的多进程模块,提供了一个Process类来代表一个进程对象;
"""
from multiprocessing import Process
from time import sleep
import os
##子进程需要执行的代码
def run(arg):
while True:
#os.getpid() 获取当前进程id号
#os.getppid() 获取当前进程的父进程
print("sunck is a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
# 面向对象编程即OOP,适合于开发大型项目;
# 类:具有某种特征的事物的集合
# 对象:类里面的个体
# 类是抽象的,对象是具体的
# 对象为类的实例化,即从抽象到具体
# 创建一个类的格式
# class 类名:
# 类里面的内容
class cl1:
pass
print(cl1)
# 输出: <class '__main__.cl1'>
# 即此时cl1就是一个类
##创建一个对象,即实例化一个类
a=cl1()
print(a)
# 输出:<__main__.cl1 object ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
import tkinter
win=tkinter.Tk()
win.title("zhl")
win.geometry("400x400+200+0")
"""
数据范围控件
"""
##绑定变量
v=tkinter.StringVar()
def update():
print(v.get())
#increment 设置步长
#values 最好不要和from_ 和 to同时使用
#command ##只要值改变,就会执行对应的事件函数;
sp=tkinter.Spinbox(win,f... |
# game.py
import string
import random
import requests
class Game:
def __init__(self):
self.grid = []
for _ in range(9):
self.grid.append(random.choice(string.ascii_uppercase))
def is_valid(self, word):
if not word:
return False
letters = self.grid.copy(... |
import patient_Data
import no_of_rows
import add_details
def database_connect(x):
print(x.uniqueid)
def getInput():
room_available = False
x = patient_Data.Patient()
database_name = "Hospital1"
name = input("Enter the name of the patient : ")
age = input("Enter the patients age: ")
diseas... |
a = float(input("Ingrese a: "))
b = float(input("Ingrese b: "))
c = float(input("Ingrese c: "))
if a>(b+c) or b>(a+c) or c>(a+b):
print(a = float(input("Ingrese a: ")))
elif a==b and b==c:
print(a = float(input("Ingrese a: ")))
elif a==b or b==c or a==c:
print(a = float(input("Ingrese a: ")))
else:
pri... |
#!/usr/bin/python
# Various common utilities
import datetime
import random
def dtime_within(dtime1, dtime2, window_s):
""" Returns whether the two datetimes are within window_s seconds of eachother """
dtime1_secs = (dtime1-datetime.datetime(1970,1,1)).total_seconds()
dtime2_secs = (dtime2-datetime.datetim... |
"""
EXTERNAL LIBRARIES
"""
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
import math
"""
INTERNAL UTIL LIBRARIES
"""
from PerceptronLearningAlgorithm import PerceptronLearningNetwork
# Add parent directory to the sys path
sys.path.append('../')
# Import any python modules from ... |
"""
EXTERNAL LIBRARIES
"""
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
import math
"""
INTERNAL UTIL LIBRARIES
"""
# Add parent directory to the sys path
sys.path.append('../')
# Import any python modules from parent directory
from utils.SingleLayerNetwork import SingleLayerN... |
'''
@Author: Leeroy P. Williams
@Version: 1
@Code_Base: Python3x
@Desc: Solve quadratic equations using the CLI
'''
import argparse
from math import sqrt
parser = argparse.ArgumentParser(description='calculates the roots of a quadratic equation')
group = parser.add_mutually_exclusive_group()
group.add_argument(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/4 10:38
# @Author : yangyuanqiang
# @File : demon1.py
age = input("Please is age: ")
if age.strip():
if age.isdigit():
if int(age) >= 18:
print("你是一个成年人!")
else:
print("你还是一个小屁孩!")
else:
print("你输入的不是... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/3 21:57
# @Author : lingxiangxiang
# @File : demon6.py
# for i in range(1, 10):
# print("{0} x {1} = {2}".format(i, i, i*i))
#1 1x1=1
#2 1x2=2 2x2=4
#3 1x3=3 2x3=6 3x3=9
# a x b = a*b
# a最小是最小为1, 最大为行号
# b等于行号
for b in range(1, 10):
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/29 22:00
# @Author : yangyuanqiang
# @File : demo2.py
# 链表和数组 数据结构中的内容
# 列表简单理解成数组
m = ["11.11", "2", "3", "a", "b", "c", "True"]
# m.append() #最后一个元素追加内容
# m.reverse() #
m.sort() #字符串进行排序
print(m.sort())
print(m)
m.pop() ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/13 23:11
# @Author : yangyuanqiang
# @File : 2.py
#2、利用while True 无限循环配置break语句,计算1 + 2 + 4 + 8 + 16 + ... 的前20项的和 脚本名:2.py
#方法一:
sum = 0
x = 1
y = 1
while 1:
if x <= 20:
x += 1
sum = sum + y
y *= 2
else:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/19 21:27
# @Author : lingxiangxiang
# @File : demon3.py
import time
import multiprocessing
def add1(lock, value, number):
with lock:
print("start add1 number= {0}".format(number))
for i in range(1, 5):
number += val... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/13 23:01
# @Author : yangyuanqiang
# @File : 1.py
#1、对100以内的两位数,请使用for循环打印出所有十位数数字比个位数数字小的数,例如,23(2 < 3) 脚本名:1.py
count = 0
for i in [1,2,3,4,5,6,7,8,9]:
for j in [0,1,2,3,4,5,6,7,8,9]:
if i < j:
count += 1
pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/21 21:51
# @Author : yangyuanqiang
# @File : demo4.py
from multiprocessing import Semaphore, Process
import time
def task(s, msg):
s.acquire()
print('hello, %s' % msg)
time.sleep(1)
s.release()
if __name__ == '__main__':
s =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/12 22:06
# @Author : yangyuanqiang
# @File : demon22.py
'''
函数的定义(声明):
函数以关键字def开头,函数名, 参数:回车缩进
def function(org1, org2, .....):
pass
函数就是一种封装的思想,把细小的功能或者可以缩小的功能封装成一种函数
函数的调用:
函数名直接传入参数就可以
function (1, 2, 3)
arg1, arg2 形参
1, 2, 3 实... |
format1=input("Enter the date format dd/mm/yy or mm/dd/yy:")
if format1 == "dd/mm/yy":
for i in range(10):
date1=input("Enter the date: ")
dd,mm,yy=date1.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm == 1 or mm == 3 or mm == 5 or mm == 7 or mm == 8 or mm =... |
#Jordan Russell
#18/11/14
#Function for calculating overtime pay
def calculate_basic_pay(hours, pay):
basic_pay = hours * pay
return basic_pay
def calculate_overtime_pay(hours, pay):
overtime_pay = (hours - 40) * (pay * 1.5)
total = overtime_pay + (40 * pay)
return total
def calculat... |
import sqlite3
import pandas as pd
import numpy as np
def makeTables(cursor):
#create the user table
cursor.execute("""DROP TABLE IF EXISTS user;""")
create_user = """CREATE TABLE user (
id INTEGER PRIMARY KEY,
age INTEGER
);"""
cursor.execute(create_user)
#create the book table
c... |
"""
In this file, I will collect all data from 'books.csv'
and insert each row into the corresponding Heroku table.
"""
import csv
from project1 import app,db
from project1.models import *
from booksetup import GoodRead
class Book(Books):
all_authors = {}
all_years = {}
def __init__(self,isbn,t... |
from PIL import Image
import os.path as path
def return_image_without_exif(image_file_input, image_file_output):
"""Takes an Image file as an argument and return image file without exif simply by resaving it"""
image = Image.open(image_file_input)
image.save(f"{image_file_output}/{path.basename(image.filen... |
nums = list(map(int, input().split()))
setT = set()
for num in nums:
if setT.__contains__(num):
print("YES")
else:
print("NO")
setT.add(num)
|
print(11 + 6)
print(11 - 6)
print(11 * 6)
print(11 ** 6) # возведение в степень
print(11 // 6) # целочисленное деление (возвращается число до запятой)
print(11 % 6) # остаток от деления
print(11 / 6) # полноценное деление
speed = 108
time = 12
distance = time * speed
print(distance) |
num1 = int(input())
num2 = int(input())
if num1 > num2:
print(1)
elif num2 > num1:
print(2)
else:
print(0)
|
number = int(input())
leftPart = number // 100
rightPart = ((number % 10) * 10) + ((number // 10) % 10)
print((leftPart - rightPart + 1)**2)
|
stave = int(input())
up = int(input())
down = int(input())
m_per_day = up - down
st_days = (stave - up - 1) // m_per_day + 1 + 1
print(st_days)
# за последний день
# улитка пройдет весь up
# поэтому уменьшаем stave
# на up
# и гарантированно добавляем 1
|
class Student:
s_name = ""
grade = 0
def read_create_stud():
s = input().split()
stud = Student()
stud.s_name = s[0]
stud.grade = int(s[1])
return stud
i = int(input())
studs = []
for k in range(i):
student = read_create_stud()
studs.append(student)
studs.sort(key=lambda x: x.g... |
num = float(input())
f_num_dig = int((num - int(num)) * 10)
if f_num_dig >= 5:
num = int(num) + 1
else:
num = int(num)
print(num)
|
import sys, pdb
from collections import Counter
from textwrap import dedent
try:
from game_of_greed.game_logic import GameLogic
from game_of_greed.banker import Banker
except:
from game_logic import GameLogic
from banker import Banker
class Game:
def __init__(self, dice_values=None):
self.... |
'''
itertools.permutations()
'''
from itertools import permutations
if __name__ == '__main__':
st, n = input().split()
sorted_list = sorted(list(permutations(st, int(n))))
print(*[''.join(c) for c in sorted_list], sep='\n')
|
'''
Zipped!
'''
if __name__ == '__main__':
num_student, num_sub = map(int, input().split())
exam_list = []
for _ in range(num_sub):
exam_list.append(list(map(float, input().split())))
for exam_result in zip(*exam_list):
print(sum(exam_result) / num_sub)
|
'''
Find Angle MBC
'''
import math
if __name__ == '__main__':
ab = float(input())
bc = float(input())
angle = int(round(math.degrees(math.atan2(ab,bc))))
print(str(angle) + '°')
|
'''
Piling Up!
'''
if __name__ == '__main__':
for _ in range(int(input())):
input()
cubes = list(map(int, input().split()))
min_cube = cubes.index(min(cubes))
left_cubes = cubes[:min_cube]
right_cubes = cubes[min_cube:]
if(left_cubes == sorted(left_cubes, reverse=T... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import rc
x = np.linspace(0,10,50)
y = np.linspace(0,10,50)
z = np.linspace(0,10,50)
u = np.sin(x)
v = np.sin(x)
w = np.sin(x)
matrix = np.zeros((len(x),6))
for i in range(len(x)):
m... |
# 1.6绘制垂直和水平柱状图
# 垂直/水平 柱状图
# bar 垂直
# barh 水平
import matplotlib.pyplot as plt
# bar(X,Y) X横坐标,Y纵坐标(值)
data = [30,53,12,45]
# X = [0,1,2,3]
# Y = [30,53,12,45]
# plt.bar(range(len(data)),data)
# plt.barh([1980,1988,1997,2001],[2000,3894,1999,5000],height=3)
hdata = [30,53,12,45]
plt.barh(range(len(hdata)),hdata)
pl... |
# 2.8控制柱状图的填充模式
import numpy
import matplotlib.pyplot as plt
'''
hatch: * x /
'''
N = 8
A = numpy.random.random(N)
B = numpy.random.random(N)
plt.bar(range(N),A,color='b',hatch = 'x')
plt.bar(range(N),A+B,bottom=A,color='r',hatch='*')
plt.show()
|
# 2.3用列表定制柱状图的颜色
import numpy
import random
import matplotlib.pyplot as plt
values = [random.randint(0,99) for i in range(50)]
color_set = ['#FF00FF','#FFFF00','r','b']
color_list = [color_set[random.randint(0,3)] for i in range(100)] # random.randint()随机整数,区间左闭右闭
plt.bar(range(len(values)),values,color=color_list)
p... |
def select_sort(list):
n = len(list)
for i in range(n):
#min = list[i]
for j in range(i+1,n):
if list[j] < list[i]:
# list[i] = list[j]
# list[j] = min
list[i],list[j] = list[j],list[i]
return list
list = [1,3,5,7,2,4,5,4,... |
#both variables are iterators. big_range is a generator, special type of iterator
import sys
#defining my own generator
def my_range(n: int):
print("my_range starts")
start = 0
while start < n:
pritn("my_range is returning {}.format(start))
yield start
start += 1
#yield returns the value... |
def calc_mean(lst):
length = len(lst)
total = sum(lst)
return round(total / length)
T = int(input())
case_lst = []
for i in range(T):
case_lst.append(list(map(int, input().split(' '))))
for i in range(len(case_lst)):
print(f'#{i+1} {calc_mean(case_lst[i])}') |
"""
파스칼의삼각형_1.py에서 반복문과 인덱스를 통해 풀었다면,
파스칼의삼각형_2.py는 스택 이용
"""
T = int(input())
for tc in range(1, T + 1):
N = int(input())
triangle_line = [1] # 처음 시작은 1
cnt = 0
print("#{}".format(tc))
while cnt < N:
print(" ".join(map(str, triangle_line)))
new_line = [] # 다음 줄을 저장할 리스트
... |
T = int(input())
def rotate_90(lst): # 배열 90도 회전 함수
N = len(lst)
rotated = [[0] * N for _ in range(N)]
for row in range(N):
for col in range(N):
rotated[row][col] = lst[N - col - 1][row]
return rotated
for tc in range(1, T + 1):
N = int(input())
data = []
for _ in ... |
def solution(s):
answer = True
temp = []
for i in s:
if i == '(': # '(' temp에 넣기
temp.append(i)
else: # ')'의 경우
if len(temp) != 0 and temp[-1] == '(': # 짝 맞은 '()' 제거
temp.pop(-1)
elif len(temp) != 0 and temp[-1] == ')':
... |
def solution(n, arr1, arr2):
answer = []
# OR 계산
for i in range(n):
answer.append(arr1[i] | arr2[i])
answer = [bin(i) for i in answer]
# #으로 전환
for i in range(len(answer)):
temp = answer[i].replace('1', '#')
temp = temp.replace('0', ' ')
answer[i] = temp
answe... |
"""
This creates a cell class for every single one of the 81 cells in a sudoku board. This is so that when playing the
game, each cell has its own and different properties that make playing easier.
Each cell has these attributes: whether or not it can be changed, its row, its column, the board_width, the board_height,... |
# crack password
# assume MD5 sum
import hashlib
from string import printable
# One lowercase letter only
answer = "e358efa489f58062f10dd7316b65649e"
for guess in printable:
encoded_guess = guess.encode('utf-8')
hashed = hashlib.md5(encoded_guess).hexdigest()
if( hashed == answer ):
print("password 1 is", guess... |
def batching(list_of_iterables, n=1, infinite=False, return_incomplete_batches=False):
"""
Takes one or more iterable inputs as argument and splits it in equally-sized chunks.
:param list_of_iterables: list of equally-sized iterables (list)
:param n: chunk size (int)
:param infinite: when set to Tru... |
#!/user/bin/env python
#-*- coding:utf-8 -*-
import knn
from numpy import *
dataset,labels = knn.creatDataSet()
input = array([1.1,0.3])
K = 3
output = knn.classify(input,dataset,labels,K)
print("测试数据为:",input,"分类结果为:",output) |
import random
import string
random.seed(0)
for i in range(3):
if i == 0:
first = []
for j in range(10):
letters = ''
for k in range(5):
letters = letters + (random.choice(string.ascii_lowercase))
first.append(letters)
if i == 1:
middle = []
for j in range(10):
letters = ''
... |
"""
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the differenc... |
"""
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
"""
from typing import List
def make_odd_fibo_numbers(values: List[int]) -> int:
result = [i for i in values if i % 2 == 0]
return sum(result)
def make_fibo(number: int)... |
#!/usr/bin/env python3
import re
# arg1=string to match against, arg2=optional str to strip()
def regStrip(arg1, *arg2):
if(arg2):
arg = arg2[0] # Get string from tuple
print('Remove: '+str(arg))
check = r'^'+str(arg)+r'*(... |
#!/usr/bin/env python3
"""Delete possibly unneeded files.
"""
import os
# Walk the tree
def walkTree(folder):
"""Walk tree and find unnecessarily large files.Walk
Arg:
folder: path that needs to be walked
"""
folder = os.path.abspath(folder)
for folder, subfolders, filenames in os... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 23:03:23 2020
@author: Deepika
"""
def RotateMat(mat):
N = len(mat)
for i in range(N):
for j in range(i+1, N):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
for i in range(N):
j = 0
k = N-1
while j < N... |
import collections
def isUnique(string):
hm = collections.Counter(string)
for elem in hm:
if hm[elem] > 1:
return False
return True
if __name__ == "__main__":
string = "abc"
print(isUnique(string))
|
import re
remove_words = []
stop_words = open('resources/stop_word.txt', 'r', encoding='utf8')
for row in stop_words:
remove_words.append(row[:-1])
def remove_word(words):
result = []
for word in words:
if (word not in remove_words):
result.append(word)
return result
|
import re
LEGAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
infile = "test.txt"
with open(infile, 'r') as f:
lines = f.readlines()
abbrev = set()
for line in lines:
line = list(line[4:].strip())
line = ['-' if c not in LEGAL else c for c in line]
line = re.split('-', ''.join(line))
for c in line:
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.