text stringlengths 37 1.41M |
|---|
import numpy as np
import curses
## Class describing our snake
class Snake:
def __init__(self, head, speed):
self.__x = [head[0]]
self.__y = [head[1]]
self.__vx = [speed[0]]
self.__vy = [speed[1]]
self.__length = 1
self.__color = 1
self.__shape = '#'
def __repr__(self):
return "Snake with length {:}... |
import numpy as np
import matplotlib.pyplot as plt
# Print statements to inform the user how the histogram is made and meant to be read
print("-" * 120)
print("Average strikes landed per fighter type histogram.")
print("-" * 120)
print("Info: This is a histogram made to showcase the average amount of strikes landed fo... |
students = ['ryu', 'crystal', 'yoshi', 'ken']
# for student in students:
# print(student)
# looping through a section of the list
# for student in students[1:3]:
# print(student)
for student in students:
if student == 'yoshi':
print(f'{student} - black belt')
break # This... |
from collections import defaultdict, namedtuple, Counter, deque
import csv
file= 'collections_directors.csv'
Movie = namedtuple('Movie', 'title year score')
directors = defaultdict(list)
with open(file) as f:
for line in csv.DictReader(f):
try:
#printing out test lines
#print("")... |
"""
import random
def main():
number = random.randint(1,10)
print "The number is",number;
main();
import random
def main():
for count in range(5):
number = random.randint(1,100);
print number;
main();
import random
MIN = 1;
MAX = 6;
def main():
again = 'y';
while again == 'y' or again == 'Y':
p... |
"""
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def hello():
tkMessageBox.showinfo("Say Hello", "Hello World")
B1 = Tkinter.Button(top, text = "Say Hello", command = hello)
B1.pack()
top.mainloop()
import Tkinter
def main():
main_window = Tkinter.Tk();
Tkinter.mainloop();
main();
sum = 0
secon... |
# In class dictionary python example
# Created on October 3d 2019
# by Aggeliki Barberopoulou
#Create this dictionary for a map legend
legend = {0:'no value',1:'deciduous',2:'conifers',3:'industrial',4:'residential',5:'water bodies',6:'agricultural'}
#Write a function that will print all the items using the following... |
#Chapter 9
9.1 Suppose you steal another item for the knapsack problem - an mp3 player weighing 1lb, worth $1000. Should you steal it?
9.2 You're going cmaping with a knapsack that'll hold 6lbs and you can take:
water/3lbs/10; book/1lb/3; food/2lb/9; jacket/2lb/5; camera/1lb/6
what is optimal set to take on camping... |
title = input('Enter a title for the data:\n')
print('You entered:\n%s'%title)
colume1 = input('Enter the column 1 header:\n')
print('You entered:\n%s\n'%colume1)
colume2 = input('Enter the column 1 header:\n')
print('You entered:\n%s\n'%colume2)
data_point = input('Enter a data point (-1 to stop input):\n')
print... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 09:48:46 2020
@author: Shamsur Rahaman
# 02_Fundamentals of python
Topics : list, slicing, tuple, function, package, slicing_array
"""
# -----------list -------------
# 1
mylist = [1,2,3,4,5,6]
print(mylist)
type(mylist)
# 2
l2 = ['hello'... |
import os,sys
os.system("cls")
i = 0
a = 5
hombres = 0
mujeres = 0
nombres = []
sexos = []
edades = []
sum_edades = 0
prom_edades = 0
print("----Inscripciones para natación----")
while (i<a):
nombre = input("Ingrese su nombre: ")
nombres.append(nombre)
sexo = input("Ingrese su sexo (H/M): ")
while ... |
# encoding=utf-8
from tkinter import *
def resize(ev=None):
label.config(font='Helvetica -%d bold' % scale.get())
top = Tk()
label = Label(top, text='hello world', font='Helvetica -12 bold')
label.pack()
scale = Scale(top, from_=10, to=40, orient=HORIZONTAL, command=resize)
scale.set(12)
scale.pack(fill=Y, ex... |
"""Queue Helper Class"""
class Queue:
# The option to initialize with just data or with pre-existing child nodes
def __init__(self, queue_list=None):
self.queue_list = queue_list
def add_to_queue(self, data):
if self.queue_list is None:
# print("Creating New Queue...")
... |
# Напишите генератор frange как аналог range() с дробным шагом.
def frange(start=0.0, stop=None, step=None):
while start < stop - step:
start = round(start + step, 1)
yield start
for x in frange(0, 5, 0.1):
print(x)
|
# Напишите программу, позволяющую ввести с клавиатуры текст
# предложения и вывести на консоль все символы, которые входят
# в этот текст ровно по одному разу.
letterDict = {}
# string = str(input("Enter the string:\n"))
string = 'Напишите программу, позволяющую ввести с клавиатуры' \
' текст предложения и вы... |
# Imports
import sys
import copy as COPY
sys.path.append('../BoardStuff')
import errors as ERROR
class Piece():
def __init__(self):
"""
Define Default Class Variables
"""
self.color = 'null'
self.name = 'null piece'
self.symbol = ' '
self.value = 0
... |
from copy import deepcopy
from math import sin, cos, sqrt, acos
class Matrix:
def __init__(self, vect1 = [1, 0, 0], vect2 = [0, 1, 0], vect3 = [0, 0, 1]):
self.data = [vect1, vect2, vect3]
def __len__(self):
return len(self.data)
def __repr__(self):
return '\n'.join(map(str, self.da... |
#Given a 32-bit signed integer, reverse digits of an integer.
# Example 1:
# Input: 123
# Output: 321
class Solution:
def reverse(self, num):
revd = int(str(num)[::-1]) if num>= 0 else -int(str(num)[1:][::-1])
if revd > 2**31 or revd < -2**31:
return 0
else:
return r... |
class Estado():
def __init__(self, estado, confirmados, negativos, sospechosos, recuperados, fallecidos, activos):
self.estado = estado
self.confirmados = confirmados
self.negativos = negativos
self.sospechosos = sospechosos
self.recuperados = recuperados
se... |
# your code goes here
import sys
#Andalu is rated at 3.
def rated_restaurants(filename): #function that takes in txt file
"""Reads a file and spits out the ratings in alph. order"""
restaurants = {} #empty dict
filename = open(sys.argv[1]) #filename opens text input
for line in filename:
... |
"""
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
"""
def solution(A):
print("Lista:", A)
if len(A) == 1:
... |
"""
A string S consisting of N characters is called properly nested if:
S is empty;
S has the form "(U)" where U is a properly nested string;
S has the form "VW" where V and W are properly nested strings.
For example, string "(()(())())" is properly nested but string "())" isn't.
... |
# Author: Abhinav Thakur
# Email : compilepeace@gmail.com
# Description: It is the main script that runs the game, calling logics and managing UI for the game.
import sys
interpreter = sys.executable.split('/')[-1]
if interpreter == 'python3':
from tkinter import Frame, Label, CENTER
else:
from Tkinter import Fram... |
# http://www.nerdparadise.com/programming/pygame/part6
#
# mouse input
import pygame
def main():
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
radius = 15
x = 0
y = 0
cmodes = ["red","green","blue"]
points = []
while True:
pressed = pygame.key.get_pressed()
alt... |
#Day 05
with open('./05.txt') as myinput:
inputlines = myinput.readlines()
seats = [line.strip() for line in inputlines]
def seat_finder(seat, min_value, max_value, direction):
value_sum = max_value + min_value
if seat[0] == direction[0]:
max_value = value_sum // 2
elif seat[0] == ... |
# # 我有 1~N 一共 N 个连续的数,每个数出现一次
# # ,比如 1,2,3,4,5,6,7,8,9.....N,
# # 现在我把它打乱,打乱的过程中丢失了一个数,
# # 请用时间/空间复杂度尽可能小的方式找出这个数
#
# # def find(a):
# # a = sorted(a)
# # n = []
# # for i in range(len(a)+1):
# # n.append(i+1)
# #
# # for j in n:
# # if j in a:
# # continue
# # else... |
# stack = [1,2,3,4]
# stack.append(5)
# stack.append(6)
# print(stack)
#
# stack.pop()
# stack.pop(3)
# print(stack)
#
# from collections import deque
# a = ["a","b","c"]
# que = deque(a)
# que.append("d")
# que.append("e")
# print(que)
#
# que.popleft()
# que.pop()
# print(que)
# list comprehensions
# lista = []
# ... |
x = int(input("请输入数字:"))
if x < 0:
print("") |
def fizz_buzzer(number):
if number%5==0 and number%3==0:
return "fizzbuzz"
elif number%5==0:
return "buzz"
elif number%3==0:
return "fizz"
else:
return number
def negfizz_buzzer(number): #created neg_fizzbuzz loop for negative numbers
if number%5==0 and number%3==0:... |
# Converts degrees Fahrenheit to degrees Celsius
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
def fahrenheit_to_celsius_convert(f):
"""
Converts degrees Fahrenheit to degrees Celsius
"""
return (f - 32) * 5 / 9
window = tk.Tk()
window.title('Fahrenheit to Ce... |
from utils import (
safe_input,
select_by_id_or_name,
today,
get_products,
update_products,
get_employees,
get_sales,
add_sale
)
def register_sale():
sale = {
"date": today()
}
print("--- Satış kaydı ---\n")
print("Urunu kim satıyor?")
employees = get_empl... |
'''
Created on 28 May 2013
@author: samgeen
'''
from Tetrahedron import Tetrahedron
def Intersect(tet1, tet2):
'''
Intersect 2 tetrahedron objects and return the intersecting volume
'''
planes = tet1.Surfaces()
tets = [tet1]
# Slice tet2 in each tet1 surface
for plane in planes:
n... |
n=int(raw_input())
t1=0
t2=1
for i in range(1,n+1):
sum=t1+t2
t1=t2
t2=sum
print t1,
|
a1=int(raw_input())
b1=raw_input().split()
if a1==len(b1):
print min(b1),max(b1)
|
n=str(raw_input())
if n in("a or A,e or E,i or I,o or O,u or U"):
print("Vowel")
else:
print("Consonant")
|
from binary_search import make_word_list
from random import random
from structshape import structshape
from exercise_11 import invert_dict
def in_both_at_same_place(word1, word2):
i = 0
count = 0
while i < len(word1):
if word1[i] == word2[i]:
count += 1
i += 1
if count == l... |
from exercise_12 import get_anagrams
from binary_search import make_word_list
import shelve
def read_anagrams(s):
words = make_word_list()
loa = get_anagrams(words)
list_of_words = []
for t in loa:
if sorted(s) == sorted(t[0]):
list_of_words.extend(t)
else:
con... |
from sklearn import preprocessing
from sklearn.neighbors import KNeighborsClassifier
# Assigning features and label variables
# # First Feature
weather=['Sunny','Sunny','Overcast','Rainy','Rainy','Rainy','Overcast','Sunny','Sunny', 'Rainy','Sunny','Overcast','Overcast','Rainy']
# Second Feature
temp=['Hot','Hot... |
# 행맨 게임
import random
words = ["apple","coffee","guitar","harmony","programmers","spaghetti"]
question = random.choice(words) #리스트인 words 값들을 입력받아 하나를 랜덤으로 리턴
letters = "" # ""도 문자
print("-"*50)
print("Welcome To Hangman Game")
print("-"*50)
life = len(question) + 2 #랜덤으로 리턴받은 단어의 글자수를 세어 2를 더함
while... |
from ...stacks_and_queues.stacks_and_queues.stacks_and_queues.stacks_and_queues import Queue
class Vertix:
def __init__(self, value):
self.value = value
class Edge:
def __init__(self, vertix, weight):
self.vertix = vertix
self.weight = weight
class Graph:
def __init__(self):
... |
y=int(input("Enter the final year"))
print("The leap years are:")
for i in range(2021,y+1):
if i%4==0:
print(i) |
n=int(input('Enter a number'))
res=n+(n*n)+(n*n*n)
print(res) |
a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
a1_sorted_keys_2 = sorted(a1, key=a1.get)
print(a1_sorted_keys)
print(a1_sorted_keys_2) |
from abc import ABCMeta, abstractmethod
class Populacao(metaclass=ABCMeta):
"""Classe base para implementação das técnicas de geração de população."""
@abstractmethod
def gerar_populacao(self, populacao_atual, percentual_mutacao, contador_geracoes):
"""Método base para ser sobreescrito nas subclas... |
import math
import random
from selecao import Selecao
class SelecaoRoleta(Selecao):
"""Classe que implementa seleção dos genes por roleta."""
__quantidade_cromossomos = 0.0
def __valor_maximo(self):
"""Retorna o valor máximo da roleta."""
return (self.__quantidade_cromossomos + 1) * se... |
import math
import random
from populacao import Populacao
class PopulacaoPreencher(Populacao):
"""Classe que implementa a geração apenas técnica de cruzamento e seleção,
apenas para preenchimento da população."""
def __init__(self, tamanho_populacao, cruzamento, cromossomo_utilidades, selecao):
... |
'''
Finds pth root of an integer x. Uses Binary Search logic. Start with a lower
bound l and go up until upper bound u. Break the problem into halves depending
on the search logic. The search logic says whether the mid (which is the mid
value of l and u) raised to the power to p is less than x or it is greater than... |
"""Built-in function-based loaders."""
import pygame
import pygame.freetype
from .core import register, loader
from .configure import get_config
@loader()
def image(filepath, *, convert_alpha=None):
"""Load an image.
Calls .convert() on the surface before returning it.
If image has alpha, .convert_alpha... |
import numpy as np
from ._CFunctions import _CMinusDay
from ._CTConv import _CTConv
def MinusDay(Date):
'''
Given an input day, this function will provide the date of the
preceeding day.
Inputs
======
Date : int
Date in the format yyyymmdd
Returns
=======
Date : int
Previous date in format yyyymmdd... |
import numpy as np
from ._CFunctions import _CWithinTimeRange
from ._CTConv import _CTConv
def WithinTimeRange(Timet,Time0,Time1,BoolOut=False):
'''
Performs a simple check on a test time (Timet) to see if it exists
between Time0 and time1.
Inputs
======
Timet : tuple | float
Test time - either a single flo... |
import pymongo #import library
client = pymongo.MongoClient("mongodb://localhost:27017") #connect to server
db = client["lib"] #connect to database
books = db["books"] #create books database
query = {
"name": "Life 3.0"
}
#print([*books.find({
# "name": "Life 3.0" #gets the book from this title
#},{
#"_id"... |
print("Welcome to my house!")
# num1 = int(raw_input("Give me side 1 length: "))
# num2 = int(raw_input("Give me side 2 length: "))
# num3 = int(raw_input("Give me side 3 length: "))
#
# def is_triangle(s1, s2, s3):
# sum1 = s1 + s2 # if greater than s3
# sum2 = s2 + s3 # if greater than s1
# sum3 = s1 + s... |
#User function Template for python3
class Solution:
def search(self, A : list, l : int, h : int, key : int):
while(l<=h):
mid=(l+h)//2
if A[mid]==key:
return mid
elif A[mid]>A[l]:
if(key>=A[l] and key<A[mid]):
h=mid-1
... |
#User function Template for python3
class Solution:
def select(self, arr, i):
mid=i
for j in range(i+1,n):
if arr[j]<arr[mid]:
mid=j
return mid
# code here
def selectionSort(self, arr,n):
for i in range(n):
j=self.select(arr... |
#User function template for Python
class Solution:
#Function to find the days of buying and selling stock for max profit.
def stockBuySell(self, A, n):
ans=[]
profit=0
for i in range(1,n):
if A[i]>A[i-1]:
temp=i-1
temp1=i
a=[temp,temp1]
a... |
from Tkinter import *
import Step1_Data_Cleaning
import Step2_Determine_Benchmarks_for_Wells
import Step3_Discrete_Linear_Fit
def close_window():
window.destroy()
def run_step_1():
Step1_Data_Cleaning.main()
def run_step_2():
Step2_Determine_Benchmarks_for_Wells.main()
def run_step_3():
Ste... |
from functools import *
from Fourth import *
numbers = []
for i in range(5):
num = int(input("Enter a list of numbers: "))
numbers.append(num)
evns = list(filter(lambda a : a % 2 == 0,numbers))
sqrs = list(map(lambda a : a * a, evns))
sum = reduce(lambda a, b : a + b, sqrs)
print(evns)
pri... |
from datetime import date
class Record:
'''
This class contains three getter methods for each of the attributes that will be initialized from
the parameters passed. Purpose of this class is to be able to represent a record.
'''
def __init__(self, Date, category, description, amount):
'''
... |
def main():
cells = list(' ')
turn = 0
print_state(cells)
while True:
coords = list(input('Enter the coordinates: ').replace(' ', ''))
make_move(coords, cells, turn)
analyze_game(cells)
turn += 1
def print_state(game):
print("---------\n" + "| " + game[0] + ... |
import os
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
from shutil import copy
import csv
def get_filename(file_path):
'''
Takes a file name path and splits on '/' to obtain only the file name.
Splits the file name from extension and returns just the us... |
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST():
def __init__(self, value):
self.head = Node(value)
self.head.left = None
self.head.right = None
def insert(self, value):
current_... |
# Ascending Order
def binary(nums,x):
low=0
high=len(nums)-1
while(low<=high):
mid=(low+high)//2
if x==nums[mid]:
return mid
elif x<=nums[mid]:
high=mid-1
else:
low=mid+1
print(binary([1,3,5,6,8,14,16],3))
# Descending Order
d... |
#!/bin/env python3
# -*- coding:utf-8 -*-
"""http://www.pythonchallenge.com/pc/ring/bell.html
<title>many pairs ring-ring</title>
<img src="bell.png" border="0"/>
<br>RING-RING-RING
<br>say it out loud</font>
"""
from PIL import Image
img = Image.open('bell.png')
img.load()
r, g, b = img.split()
gdata = list(g.getdat... |
#!/bin/env python3
# -*- coding:utf-8 -*-
"""http://www.pythonchallenge.com/pc/return/mozart.html
http://www.pythonchallenge.com/pc/return/mozart.gif
let me get this straight
图片中有一些粉红色的小块块,通过在行上移动像素,使所有的粉红色块块排成一列。
值得注意的是给出的图像是一个索引图像,因此读取图像数据之后的内容不是RGB值,而是索引值,在这幅图像中粉红色对应的索引值是195。
移动方法:将一行从第一个索引值为195的点到最右边的点移动到行首,而点左边的内容... |
#!/bin/env python3
# -*- coding:utf-8 -*-
"""http://www.pythonchallenge.com/pc/return/uzi.html
1*6年1月26日周一,第二天是某人的生日。这一年的二月还是闰月。
<!-- he ain't the youngest, he is the second -->
问,谁在1*6年1月27日周二出生?
106到1996年,10年步进,而且必须是4的倍数。
[156, 376, 556, 776, 956, 1176, 1356, 1576, 1756, 1976]
倒数第二个年份,所以是1756年1月27日周二。莫扎特 mozart
"""... |
"""
A ideia aqui é criar funções que facilitam o processamento de informações pelo robot
mesmo que dê para fazer no robot, se for muito trabalhoso, basta criar uma função em python,
inserir aqui, e importá-la para evitar código "sujo"
"""
def comparaStrings(s1, s2):
return s1 == s2
#def pegaArquivo(caminho):
# ... |
#! /usr/bin/env python3
"""
Tuenti Challenge 4, Apr 2014, Challenge 4 - Shape shifters
"""
import sys
def solve(source,target, safe):
cache = set()
bfs = [[source]] # breadth-first search tree
while bfs:
states = bfs.pop()
current = states[-1]
if one_change(current, target):
... |
#!/usr/bin/python3
""" python script that returns informatin about a given employ """
import requests
import sys
if __name__ == "__main__":
""" main method to display inormation about a given employ """
url = "https://jsonplaceholder.typicode.com/"
users = requests.get(url + "users/{}".format(sys.argv[1]... |
#!/usr/bin/python3
""" a module to find the number of subscriber of a given subreddit """
import requests
def top_ten(subreddit):
""" a method to find the number of a subscriber of a subreddit """
url = "https://www.reddit.com/r/{}/hot.json".format(subreddit)
agent = {'User-Agent': 'Python/requests'}
... |
# 4-9, Practice 4.1
# def sum(arr):
# if len(arr) == 1:
# return arr[0]
# else:
# return arr.pop(0) + sum(arr)
# Book Solution
def sum(list):
if list == []:
return 0
else:
# list[1:] => slice, from index 1 to end
return list[0] + sum(list[1:])
test_array = [2,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 14:32:18 2020
@author: noahlefrancois
"""
import numpy as np
def simpson(f, a, b, n=2):
"""
Integrate f from a to b using Simpson's rule by splitting into two rectangles
"""
#Handle the interval cases
if a == b:
retu... |
def naturals():
counter = 1
while True:
yield counter
counter += 1
def gen_spiral():
c = naturals()
yield next(c)
space = 1
while True:
for i in xrange(4):
for i in xrange(space):
next(c)
yield next(c)
space += 2
g = gen_... |
import math
def solution(n):
answer = 0
three = []
while n > 0:
three.append(n % 3)
n = n // 3
three.reverse()
for i in range(len(three)):
answer += three[i] * math.pow(3, i)
return int(answer)
print(solution(45))
print(solution(123)) |
def solution(n, m):
answer = []
for i in range(n, 0, -1):
if m % i == 0 and n % i == 0:
answer.append(i)
break
for i in range(n, n * m + 1, n):
if i % m == 0:
answer.append(i)
break
return answer
print(solution(3, 12))
print(solution(2... |
class CoffeeMachine:
def __init__(self):
self.dollars = 550
self.water = 400
self.milk = 540
self.cb = 120
self.cups = 9
self.things = ["water", "milk", "coffee beans", "cups", "money"]
def menu(self):
while True:
action = input("\nWrite act... |
import urllib.request
import pandas as pd
"""
This file is to scrape images of meals.
"""
RECIPE = pd.read_csv('recipe_clean.csv')
def download_img(url, idMeal):
"""Download and save images to the foloder.
Arguments:
url {string} -- url of image to be downloaded
idMeal {string} -- correspondi... |
import random, os, sys, time
with open(os.path.join(sys.path[0], "hmWords.txt"), "r") as f:
Words = f.read().splitlines()
#Defining Reset
def Reset():
global newWord, CurrentOutput, CorrectGuesses, Remaining, ClearWord
ClearWord= Words[random.randint(0, 199)]
newWord = list(ClearWord)
Curren... |
# docker run --rm -v $PWD:/workdir -w /workdir python:3.9-slim python 3b.py
from functools import reduce
def countTrees(grid, slope):
x_s, y_s = slope
x = 0
y = 0
trees = 0
while y < len(grid) - 1:
x = (x + x_s) % (len(grid[0]) - 1)
y += y_s
if grid[y][x] == "#":
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 00:32:29 2018
@author: kifli
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
dataset = pd.read_csv('Position_Salari... |
"""
创建外星人对象
"""
import pygame
from setting import Setting
from pygame.sprite import Sprite
class Alien(Sprite):
def __init__(self,game_setting:Setting,screen):
super(Alien,self).__init__()
self.game_setting = game_setting
self.screen = screen
#创建外星人
self.image = pygame.image... |
import numpy as np
def _discount_accum_reward(rewards, gamma=0.99, initial_running_add=0.0):
""" discounted the reward using gamma
Args:
rewards: list of reward,
gamma: discount factor
initial_running_add: the initial value to add
Returns:
list of discounted return
"""
... |
import unittest
from calculator import Calculator
class TestStringMethods(unittest.TestCase):
def test_add(self):
c = Calculator()
self.assertEqual(c.add(3, 3), 6)
def test_add2(self):
c = Calculator()
self.assertEqual(c.add(12, -10), 2)
def test_add3(self):
c = ... |
#!/usr/bin/python
# A class for taking a set of 2-element tuples, and plotting them as
# circles in an SVG file for inspection (or conversion to DXF for CNC
# fun times, or...)
# This was initially created for fiddling with Penrose-tiling-based
# sheet metal art.
import svgwrite
class SvgPlotter(object):
def __i... |
# 用来熟悉循环体结构
# 遍历str
name = "liujiujiu"
for x in name:
print(x, end="\t")
# 读取列表
a = ["a", "b", "c", "d"]
for i in range(len(a)):
print(i, a[i])
# 计数器
n = 100
sum = 0
couter = 1
while couter <= n:
sum = sum +couter
couter += 1
print("1到%d计数结果为:%d" % (n, sum))
|
from regular_expression import start_with_a_end_with_b, words_with_pt_es, words_with_consecutive_a_or_e, words_with_3a,\
words_with_3_or_more_vowel, equal_vowel_and_consonant, alphanumeric
def test():
strings = '''the red brown fox went to the apple and saw a testament of space and point and plant and pterodac... |
import random
import string
import names
import csv
myfile = open("output.csv", "w", newline='')
def generatedot(email):
if len(email) <= 1:
yield email
else:
head, tail = email[0], email[1:]
for item in generatedot(tail):
yield head + item
yield head + '.' + item
email = str(in... |
# write a function to generate all the possible k-mer combinations of DNA given k
#nucleotides = ['A', 'T', 'G', 'C']
#for i in range(1, 3):
# combinations = itertools.product(*itertools.repeat(nucleotides, i))
# for j in combinations:
# print(j)
import itertools
def kmer(x):
perm... |
#!/usr/bin/env python
# coding: utf-8
# In[118]:
student_marks=[[89,43,39],[56,79,90],[87,65,68],[56,34,89],[87,89,72]];
print("marks of student in maths,physics,chemestry:")
print(student_marks)
total_student=5
print("total_student=",total_student)
final_grade=[]
# In[119]:
count1=0
sum1=0
passed_student=0
fai... |
s="helloWorld"
rs=""
'''
for i in range(len(s)-1,-1,-1):
print(s[i],end="")
print()
'''
for i in range(len(s)-1,-1,-1):
rs=rs+s[i]
print(rs)
'''
s=rs
print(s)
print(s is rs)
''' |
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
jewelSet = set()
for jewel in J: jewelSet.add(jewel)
num = 0
for stone in S:
if stone in jewelSet:
... |
# 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 flipEquiv(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rty... |
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
self.cache = dict()
return self._recurse(0, n)
def _recurse(self, ind, n):
if ind == n:
return 1
if ind > n:
return 0... |
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
myStack = []
count = 0
for char in S:
if char == '(':
myStack.append(char)
else:
if len(myStack) > 0:... |
# 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 levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
... |
class Solution(object):
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for i, innerlist in enumerate(A):
innerlist = innerlist[::-1]
for j, elements in enumerate(innerlist):
if elements == 0:
... |
# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root ... |
from collections import defaultdict
from collections import deque
class Graph(object):
def __init__(self):
self.graph = defaultdict(list)
def AddEdge(self, u, v):
if v not in self.graph[u]:
self.graph[u].append(v)
def BFS(self, u):
if u not in self.graph.keys(): return
visited, queue = s... |
# 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 longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None: return None
... |
class Solution(object):
def rotatedDigits(self, N):
counts = 0
for num in range(1, N+1):
number = str(num)
if '3' in number or '7' in number or '4' in number:
continue
if '2' in number or '5' in number or '6' in number or '9' in number:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.