text stringlengths 37 1.41M |
|---|
"""
Name: Robin Groot
Version: 1.1
Inputs: Number start, Number end, Amount of guesses, Your guesses
Outputs: Random number, Too low or to high
Description: Random number guesser with hints and you can chooses the range to choose from.
"""
import random
# Making variables
guessed_rig... |
import pandas as pd
df = pd.DataFrame({'rainy': [.4, .7],
'sunny': [.6, .3]
},
index=["rainy", "sunny"])
print df
#for two transitions
print df.dot(df)
print ""
print "starting market example"
print ""
# bull bear stag
#bull 0.9 0.075 0.025
#bear 0.15 0.8 ... |
import unittest
# the analyze function takes in an var arguent of numbers
# it should return a dicitonary of {'mean':0,'median':0,'mode':0,'largest':0,'smallest':0}
def analyze(*nums):
pass
########################### TESTS ##############################################################
class TestMethods(unittest.... |
#########################################################################
#-*- coding:utf-8 -*-
# File Name: _study_dict.py
# Author: buptxiaomiao
# mail: buptxiaomiao@outlook.com
# Created Time: 2016年03月19日 星期六 14时09分00秒
#########################################################################
#!/usr/bin/env python2.7... |
##################################################
#-*- coding:utf-8 -*-
# FileName: recursion.py
# Author: buptxiaomiao
# Mail: buptwjh@outlook.com
# Created Time: 2017年03月08日 星期三 16时22分09秒
##################################################
#!/usr/bin/python2.7
import random
def factorial(n):
if n == 1 or n == 0... |
"""
Inheritance allows you to access attributes and methods from parent class
We can create subclasses, overwrite a new functionality
"""
class Employee:
# Class variable
raiseAmount = 1.04
numberOFEmployees = 0
# Contructor
def __init__(self, fname, lname, pay):
# It... |
from tkinter import *
from tkinter import messagebox
def clear_entry():
accountentry.delete(0, 'end')
def qualify():
amount = accountentry.get()
try:
amount = int(amount)
if amount > 3000:
messagebox.showinfo("feedback", "congragulations! you qualify for maleysia")
e... |
from collections import Counter
from itertools import combinations
def sherlockAndAnagrams_2(s):
count = []
for i in range(1, len(s)+1):
a = ["".join(sorted(s[j:j+i])) for j in range(len(s)-i+1)]
b = Counter(a)
count.append(sum([len(list(combinations(['a']*b[j], 2))) for j in b]))
r... |
import networkx as nx
import matplotlib.pyplot as plt
def main():
with open('input.txt') as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
lines = sorted([(x[5], x[36]) for x in lines])
parents = {x[0] for x in lines}
children = {x[1] for x in lines}
parents - children
... |
n = int(input())
while n <= 5 and n > 2000:
n = int(input())
for i in range(1, n + 1):
if i % 2 == 0:
square = i**2
print(str(i) + '^' + '2' + ' = ' + str(square))
else:
continue
|
mae = int(input())
a = int(input())
b = int(input())
c = mae-a-b
if a > b and a > c:
print(a)
if b > a and b > c:
print(b)
if c > a and c > b:
print(c)
|
trips = input().split()
a = int(trips[0])
b = int(trips[1])
c = int(trips[2])
# 0 = presente
# Caso 1: duas trips, de mesmo valor (volta para o presente)
if (a-b == 0) or (a-c == 0) or (c-b == 0):
print('S')
# Caso 2: três trips que voltam para o presente:
elif ((a+b) - c == 0) or ((a+c) - b == 0) or ((b+c) - a... |
def insertion_sort(arr):
n = len(arr)
for i in range(n):
for j in range(i, 0, -1):
if arr[j] < arr[j - 1]:
temp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = temp
else:
break
arr = [1, 9, 12, 0, 5, 8, 7, 2]
insertion_s... |
def selection_sort(arr):
n = len(arr)
for i in range(n):
m_idx = i
for j in range(i + 1, n):
if arr[j] < arr[m_idx]:
m_idx = j
temp = arr[i]
arr[i] = arr[m_idx]
arr[m_idx] = temp
arr = [1, 9, 12, 0, 5, 8, 7, 2]
selection_sort(arr)
print(arr)... |
def read():
total = 0
with open('input.txt') as f:
for line in f:
line = line.strip()
tokens = line.split()
print(tokens)
name = tokens[0]
num = int(tokens[1])
single = int(tokens[2])
total += num * single
p... |
class SalaryRecord:
name = 'unknown'
work_hours = None
wage = 0
def __init__(self, name):
self.name = name
self.work_hours = [0 for i in range()]
def workHour(self, day, hour):
self.work_hours[days] = hour
def setWage(self, wage):
self.wage = wage
def weekWage... |
import csv
from sys import argv, exit
if len(argv) != 3:
print("Usage: python dna.py data.csv sequence.txt")
exit(len(argv))
with open(argv[1], "r") as csvf:
reader = csv.reader(csvf, delimiter=',')
row_count = 0
for row in reader:
if row_count == 0:
# head is array of avaliabl... |
person_info={'ВИКТОР':'+77777777777',
'НУРБОЛ':'+77072344565',
'ИСКАНДЕР':'+77024162892'}
name=input()
name=name.upper()
if name in person_info:
print(person_info[name])
else:
print('Такого имени нет')
|
# По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из
# этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или
# равносторонним.
length_1 = float(input('Введите длину первой стороны треугольник... |
'''1. Реализовать функцию, принимающую два числа (позиционные аргументы)
и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть
обработку ситуации деления на ноль.
'''
# -------------------------- Выполнение -------------------------
# ----------------------------Вариант 1----------------------... |
'''
1. Поработайте с переменными, создайте несколько, выведите на экран,
запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
'''
# Выполнение
town = input("В каком городе вы живете? ")
age = int(input("Cколько лет вы живете в своем городе? "))
print("Все понятно. Вы живёте в ... |
from collections import Counter
def part1(string):
"""Count how many times we go up and down and return what floor we end up on"""
counts = Counter(string)
return counts['('] - counts[')']
def part2(string): # best solution is probably linear
"""Return the 1-indexed position of the first instruction t... |
"""
The command module handles the execution of the user-supplied commands via the
command-line interface (main application). In particular, this module takes the
parsed docstrings and outputs them to plain-text, markdown, or json.
"""
class Command(object):
"""
Executes the commands provided on the command lin... |
#! /usr/bin/python
import json
import urllib
import re
import nltk
from nltk.tag import pos_tag
from collections import defaultdict
import datetime
import xml.etree.ElementTree as ET
# json file is in utf-8 format
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
'''
Notes for our group...
- The first approach... |
#snake and ladder
import random
a=random.randint(1,6)
count=0
while(count<=100):
a=random.randint(1,6)
if (count>=94):
if (count+a==100):
print ("you won the game")
break
if (a<=100-count):
count=count+a
print (count)
else:
count=count+a
print (count)
if count==8:
pr... |
# Angeline Hidalgo
# February 2, 2020
# Defines set variables for different days of the week from 0 - 6.
# 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday
def which_day(start, nights):
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Fri... |
def SpiralMatrix(A):
'''
A-> Array taken as input which is a 2D Array
k -> Starting of Row Index
l -> Starting of Column Index
m -> No. of rows/End of Row Index
n -> No. of columns/ End of Column Index
'''
m=len(A)
n=len(A[0])
k,l = 0,0
while (k < m and l < n):
... |
# -*- coding:utf-8 -*-
# /usr/bin/python
'''
@Author : Yan Errol
@Describe:
@Evn :
@Date : 2019-07-24 23:54
'''
from queue import Queue
import threading
import time
def thread_job():
print("thread 1 Start \n")
for i in range(10):
time.sleep(0.1)
print("thread 1 finish \n")
def thr... |
# coding=utf-8
# /usr/bin/python
'''
Author:Yan Errol
Email:2681506@gmail.com
Wechat:qq260187357
Date:2019-04-11--23:32
Describe:
'''
import time
def quick_sort (alist,start,end):
"""快速排序"""
# 递归的退出条件
if start >= end:
return
mid = alist[start]
# low 为序列左边的由左向右移动的游标
l... |
# coding=utf-8
# /usr/bin/python
'''
Author:Yan Errol
Email:2681506@gmail.com
Wechat:qq260187357
Date:2019-04-11--18:06
Describe:
'''
import time
class Queue(object):
def __init__(self):
"""queue def"""
self.items = []
def is_empty(self):
""" 判断是否为空 """
return self.items == []... |
"""
This module provides utility functions for the notebooks of
the Collatz library.
"""
# Imports
import sys
import random as rnd
import pandas as pd
# Fix possible import problems
sys.path.append("..")
def set_default_pd_options():
"""
This functions sets default options for pandas.
:return: None.
... |
numbers = [10, 20, 30, 40, 50]
print(numbers[0])
numbers[1] = 'shailesh'
print(numbers)
for _ in numbers:
print(_)
max = numbers[0]
for num in numbers:
if num > max:
max = num
print(max)
from array import *
print(dir(array))
array1 = array('i', [10, 20, 30, 40, 50])
for i in array1:
print(i)... |
# list are ordered
a = ['foo', 'bar', 'baz', 'qux']
b = ['baz', 'qux', 'bar', 'foo']
print(a == b)
print(a is b)
print([1, 2, 3, 4] == [4, 1, 3, 2])
#Lists Can Contain Arbitrary Objects
a = [21.42, 'foobar', 3, 4, 'bark', False, 3.14159]
# declare empty list
my_list = []
# declare list of integers
my_list = [1, 2,... |
"""https://adventofcode.com/2020/day/1"""
import itertools
from functools import reduce
with open("input.txt", "r") as read_input:
INPUT = list(map(int, read_input.readlines()))
def expense(exps: list, entries: int) -> int:
"""find the two entries that sum to 2020 and then multiply those two numbers together... |
electricity_bill = float(input('How much was the electricity bill? '))
heat_bill = float(input('How much was the heat bill? '))
total_bill_amount = electricity_bill + heat_bill
person_1_name = input('What is the first person\'s name? ')
person_2_name = input('What is the second person\'s name? ')
person_1_days_in_the... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 10 13:41:08 2021
@author: meghagupta
"""
#1.print 1 to 10 numbers
i=1
while i<=10:
print(i)
i=i+1
#2.Using break in while loop
i=0
while i<6 :
i+=1
if i==3 :
break
print(i)
#2.Using continue in while loop
i=0
w... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 9 10:10:03 2021
@author: meghagupta
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig,ax=plt.subplots() #subplots func is used to draw multiple graphs
ax.plot(X,X**2,label='Y=X**2')
ax.plot(X,X**3,label='Y=... |
# gozerbot/examples.py
#
#
""" examples is a dict of example objects. """
__copyright__ = 'this file is in the public domain'
# basic imports
import re
class Example(object):
""" an example. """
def __init__(self, descr, ex):
self.descr = descr
self.example = ex
class Examples(dict):
... |
from abc import ABC, abstractmethod
import numpy as np
''' The abstract node class which holds an entire layer of nodes.
'''
class AbstractNode():
''' Constructor for the abstract node class
@param NumNeuronsInLayer - The number of neurons in the layer
'''
def __init__(self, NumNeuronsIn... |
import gmpy2
def encryptChar(xChar, a, b):
x = ord(xChar) - ord('a') # Use 'a' as 0
return (chr( (5*x+7)%26 + ord('a') )) # Undo shift
def encryptString(string, a, b):
result = ""
for i in range(len(string)):
result+=(encryptChar(string[i], a, b))
return (result)
def decryptChar(xChar, a,... |
# program to map the collatz conjecture steps for a given input
# variables
Var1 = 0
# For even numbers
def even(x):
return x / 2
# For odd numbers
def odd(x):
return (x * 3)+1
#introduction
print ("Collatz Conjecture:")
print ("If a number is even, n/2")
print ("If a number is odd, 3n+1")
Var1 = int(input... |
import pandas as pd
import requests
#Data loader functions belong here. This is where
# information about the data files is found.
def load_from_file():
#Each dataset may have its own loader function like this.
#This function returns a dataframe.
#First, we identify the file. Small files will be local.
... |
def discounted(price, discount, max_discount=20):
price = abs(float(price))
try:
discount = abs(float(discount))
max_discount = abs(int(max_discount))
if max_discount > 99:
return price
except(ValueError, TypeError):
print("Максимальная скидка не больше 20!!!")
... |
import requests #to request the json data from the site it is at
import json #to save data format as
#gets and saves a json file of the champions and info about them
def items():
line = open("../../../nsr/key/key.txt", "r")
key = str(line.readline()).rstrip()
line.close
r = requests.get("http... |
# Демонстрирует запись в файл
print("Создание текстового файла методом write().")
text_file = open("write_it.txt", "w", encoding = "utf-8")
text_file.write("Строка 1\n")
text_file.write("Это строка 2\n")
text_file.write("Этой строке достался номер 3\n")
text_file.close()
print("\nЧтение нового файла.")
text_file = ope... |
class ChestFactory(object):
__GOODS = ["Щит","Меч", "Булава", "Кирка","Броня" ,"И так далее"]
class Chest(object):
__chestIsEmpty = "Сундук пуст!"
def __init__(self, thing):
self.__thing = thing
self.__isOpened = False
self.__isEmpty = False
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Merwan ROPERS
#
#
# Script permettant de récupérer la capacité des salles de Spectacle en France
# depuis la page Wikipedia : https://fr.wikipedia.org/wiki/Liste_de_salles_de_spectacle_en_France
# Mode d'emploi :
# $ ./wiki_split.py
# * ./wiki_split.py Nom_du_fichier_de... |
import math
import random
title = "The Meaning of life"
print(math.pi)
print(math.sqrt(85))
print(random.random())
print(random.choice([1,2,3,4,5]))
print('--------------------------')
S = 'Spam'
len(S)
print('0 = ' + S[0])
print('1 = ' + S[1])
print('-1 = ' + S[-1])
print('-2 = ' + S[-2])
print('1:3 = ' + S[1:3])
p... |
# 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 traversal(self,depth,root):
if root == None:
return
if len(self.ret) <= depth:
... |
import sqlite3
from sqlite3 import Error
class database:
@staticmethod
def create_connection():
"""Create a connection with SQLite database
:param self: database class
"""
try:
connection = sqlite3.connect('./resources/db/bem-barato.db')
return connec... |
class Tier:
def __init__(self, name, beine):
self.name = name
self.beine = beine
def __str__(self):
return "Das Tier {} hat {} Beine.\n".format(self.name, self.beine)
Mensch = Tier("Mensch", "2")
Spinne = Tier("Spinne", "8")
Maus = Tier("Maus", "4")
tierliste = [Mensch, ... |
from tkinter import * #tkinter is used for GUI
from tkinter import messagebox #messagebox used for error boxes or for showing important information
from RI import RI #Personally made Class which solve the Route Inspection problem
from graph import Window #Personnaly ma... |
from tkinter import * #tkinter is used for GUI
from tkinter import messagebox #messagebox used for error boxes or for showing important information
from CPA import Network, Activity #Personally made classes are used to solve the actual problem with given inputs
import sqlite3 as sql ... |
# Question:
# Use a list comprehension to square each odd number in a list. The list is input by a sequence
# of comma-separated numbers.
# Suppose the following input is supplied to the program:
# 1,2,3,4,5,6,7,8,9
# Then, the output should be:
# 1,3,5,7,9
print "\nEnter sequence of numbers: "
numbers = raw_... |
a = [1, 2, 3]
b = [3, 4, 5, 1]
print set.intersection(set(a), set(b))
c = ["Chetan", "che"]
d = ["chetan", "Chetan"]
print set.intersection(set(c), set(d))
|
# Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
# Suppose the following input is supplied to the program:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Then, the output should be:
# 2:2... |
## IMPORTS GO HERE
## END OF IMPORTS
#### YOUR CODE FOR is_prime() FUNCTION GOES HERE ####
def is_prime(x):
num=0
num=int(x)
if(num!=x):
return False
if x== 2:
return True
if x%3==0:
return False
if x==1:
return False
for i in range(3,x):
... |
from string import Template
from quorumtoolbox.utils import fs_utils
def template_substitute(template, kwds, write=True):
"""
String template substitution either from file or string.
:param template: File name or string template literal. For file, the content of the file is treated
as the template.
... |
# 5-Write a program to sort a list of dictionaries using Lambda.
# Original list of dictionaries :[{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': '2', 'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}]
dict = [{'make':'Nokia', 'model':216, 'color':'Black'}, {'make':'M... |
pr=int(input())
sum=0
t=pr
while t>0:
digit=t%10
sum+=digit**3
t//=10
if pr==sum:
print("yes")
else:
print("no")
|
p = int(input(''))
for i in range(p):
print('Hello')
|
# A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.
# You are given an integer array... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 00:01:53 2019
@author: Puneet
"""
input_list = list(input("enter elements").split(","))
input_tuple = tuple(input_list)
print("list:",input_list)
print("tuple:",input_tuple) |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 16:38:14 2019
@author: Puneet
"""
import random
fruit_list = ["apple","banana","pears","watermellon","pineapple","grapes","orange"]
item = random.choice(fruit_list)
item_list = list(item)
print(item_list)
print("enter any character of your choice")
for i in range(0,len... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 18:50:20 2019
@author: Puneet
"""
# car travelled in km
car_kilometer = int(input("car travelled in kilometer:"))
# cost of diesel
cost_diesel = int(input("cost of diesel:"))
# car average
car_average = int(input("average of car:"))
# cost of travelling
total_cost = (c... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 18:40:49 2019
@author: Puneet
"""
# todays temperature in centigrade
temp_centigrade = int(input("temperature in jaipur:"))
# temperature in fahrenheit and kelvin
temp_fahrenheit = temp_centigrade*(9/5)+32
temp_kelvin = temp_centigrade + 273
print("temperature in fahre... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 16:31:29 2019
@author: Puneet
"""
list1 = []
while True:
elements = input("enter details:")
if not elements:
break
name, age, marks = elements.split(",")
list1.append((name,int(age),int(marks)))
list1.sort()
print(list1)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 18:02:24 2019
@author: Puneet
"""
name = input("enter name:")
index_info = name.index(" ")
print(index_info)
print(name[index_info+1::],"",name[0:index_info:]) |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 18:32:46 2019
@author: Puneet
"""
# my height and weight
my_height = float(input('\u0932\u0951\u092C\u093E\u0908:'))
my_weight = int(input('\u0935\u091C\u0928:'))
# calculate bmi value
bmi_value = (my_weight/my_height)/my_height
print(bmi_value) |
#coding:utf-8
class Solution:
def shell_sort(array):
gap = len(array)
while gap > 1:
gap = gap // 2
for i in range(gap,len(array)):
for j in range(i%gap,i,gap):
if array[i] < array[j]:
array[i],array[j] = array[j],a... |
from Tools.scripts.treesync import raw_input
lista = ['prueba', 'hola', 'guatemala', 'test']
lista2 = []
def caja_seleccion():
while True:
print(lista)
param = raw_input("Ingresa tu opcion")
for i in lista:
if (param.__contains__(i)):
return lista.index(i)
prin... |
def extract_month(str_fecha):
months = {
'01': 'Enero',
'02': 'Febrero',
'03': 'Marzo',
'04': 'Abril',
'05': 'Mayo',
'06': 'Junio',
'07': 'Julio',
'08': 'Agosto',
'09': 'Septiembre',
'10': 'Octubre',
'11': 'Noviembre',
'... |
import math
def distancia(x1, x2, y1, y2):
distancia = math.sqrt(pow((x2-x1),2)+pow((y2-y1),2))
print(distancia)
distancia(2,3,4,2) |
import turtle
turtle.shape('turtle')
import math
turtle.speed(10)
def ex7():
for i in range(720):
turtle.forward(i**(1/7))
turtle.left(1)
ex7()
|
class Reducer:
def __init__(self, moves):
self.moves = moves
def is_inverse_move(self, move1, move2):
if move1 + "'" == move2:
return True
return False
def is_same_move(self, move1, move2):
return move1[0] == move2[0]
def give_valid_amount(self, move, amoun... |
#Client Portal
#expand based on functions and comunictaion dicussed 8/2/20
def dec2bin(n):
#converts a decimal number to binary
s=''
while n!=0:
s= str(n%2)+s
n= n//2
l= 8-len(s)
while l>0:
s= '0'+s
l=8-len(s)
return s
N= 101 #or random large prime
a... |
# Эта программа помогает лаборанту в процессу
# котроля температуры вещества
# Именованная константа, которая представляет максимальную
# температуру
MAX_TEMP = 102.5
# Получить температуру вещества
temperature = float(input('Введите температуру вещества в градусах Цельсия: '))
# пока есть необходимость, инструктир... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 转置二维数组
original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*original)
print(list(transposed))
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 合并字典
d1 = {'a': 3}
d2 = {'b': 5}
print(**d1, **d2)
print(d1.items())
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1) |
#Write a function that will shift an array by an arbitrary amount
#using a convolution (yes, I know there are easier ways to do this).
#The function should take 2 arguments - an array, and an amount by
#which to shift the array. Plot a gaussian that started in the centre
#of the array shifted by half the array length ... |
# Extracts a color palette from a given link to an image, and paints lines with that color palette.
# Usage example: python3 16_draw_circles.py -u https://data.whicdn.com/images/247170900/original.jpg -w 20
from haishoku.haishoku import Haishoku
from PIL import Image, ImageDraw
import random
from random import randran... |
__author__ = 'marcellovirzi'
# The program compares the results of three search
# methods of approximation of the square root
# (in terms of number of iterations).
#
# The methods are:
# 1) exhaustive enumeration
# 2) bisection search
# 3) newton - raphson method
def root_exhaustive_enum(x, power, epsilon=0.01):
... |
#prompt user for a single grocery item
# append to grocery list
# groceries = []
# new_item = input('Please add a grocery item to the list: ')
# groceries.append(new_item)
# print(groceries)
#in an infinite while loop, prompt user for an item
#append the item to the list
#print the list after you add the item
#will... |
K = raw_input("input the Key:")
Key = []
[Key.append(i.upper()) for i in K if ((ord(i.upper())>64 and ord(i.upper())<91)and (i.upper() not in Key))]
[Key.append(chr(i+65)) for i in range(26) if chr(i+65) not in Key]
print "Your Key is :","".join(Key)
SRC = raw_input("Input the Message:")
Code = ""
for i in SRC:
i = i.... |
def merge_sort(list_, key=None, reverse=None):
'''
# 方法1
if len(list_) <= 1:
return list_
def merge(left,right):
r, l=0, 0
result=[]
while l<len(left) and r<len(right):
if left[l] <= right[r]:
result.append(left[l])
l += 1
... |
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
WORD_LEN = len(word)
# Null case
if WORD_LEN == 0:
return True
HEIGHT = len(board)
WIDTH = len(board[0])
def _in_bounds(coord: tuple) -> bool:
... |
class Solution:
def reverseWords(self, s: str) -> str:
output = []
current_word = ""
for char in s:
if char == " ":
if current_word:
output.insert(0, current_word)
current_word = ""
else:
current... |
import functools
def add(n):
def _(f):
@functools.wraps(f)
def __(*a, **b):
return f(*a, **b) + n
return __
return _
def multiply(n):
def _(f):
@functools.wraps(f)
def __(*a, **b):
return f(*a, **b) * n
return __
return _
def sub... |
def compress(some_string: str) -> str:
"""
Compresses `some_string` using a naive compression algorithm, which converts
continuous runs of characters to
`"{}{}".format(character, number_of_continuous_appearances)`
The flaw with this approach is that it is impossible to correctly decompress
a s... |
# Figure out which words appear most often in the headlines.
import read
import collections
df = read.load_data()
#print(df.head())
# Make headlines list
headlines = df['headline'].tolist()
#print(headlines[0])
result = ''
# Combine all headlines in list into one string
for h in headlines:
result += str(h) + ' ... |
# Determine the percentage of enrollment that each race and gender
# makes up.
import pandas as pd
enrollment = pd.read_csv('data/CRDC2013_14.csv', encoding='latin-1')
# Gender Profile in School
enrollment['total_enrollment'] = enrollment['TOT_ENR_M'] + enrollment['TOT_ENR_F']
all_enrollment = enrollment['total_enr... |
board = [' ' for x in range(10)]
def forletter(letter, pos):
board[pos] = letter
def userturn():
run = True
while run:
move = input('Please Enter Your Position in (1-9).')
try:
move = int(move)
if move > 0 and move < 10:
if isposempty... |
"""Includes
1) Sudoku Puzzle Generator
2) values_to_grid function
"""
import random
from solution import (
boxes,
reduce_puzzle,
solve,
display,
grid_values
)
def create_puzzle(N=80, diagonal=False):
"""Create a sudoku puzzle with N filled places, recursively
Args:
N (int,... |
from Inventory import Inventory
class Item(Inventory):
def __init__(self, inventory_Id, inventory_value, inventory_Slot, available_Item):
Inventory.__init__(self, inventory_Id, inventory_value, inventory_Slot)
self.available_Item = available_Item
def inventory_Item(self, pack, item):
I... |
# Steven Swiney
# TestFile to learn
print("This program is just testing the basic operations in python")
print("\n")
print("As well as seeing when variables are assigned and such since it's a line-by-line interpreter")
print("\n")
print("\n")
x = 1
y = 4
z = 149
a = z // y
print(a)
print(a + x + y)
a=5
print(a)
# S... |
a=2
b=3
if a>b:
print ('a big')
elif a==b:
print ('相等')
elif a<b:
print ('b big')
else:
pass
|
#There is a sequence of words in CamelCase as a string of letters,s , having the following properties:
#It is a concatenation of one or more words consisting of English letters.
#All letters in the first word are lowercase.
#For each of the subsequent words, the first letter is uppercase and rest of the letters are low... |
# encoding: utf-8
import distance
class Levenshtein:
def getDistance(self,word1,word2):
wordList1=list(word1)
wordList2=list(word2)
if len(wordList1)==0 or len(wordList2)==0:
x=max(len(wordList1),len(wordList2))
else:
if wordList1[-1]==wordList2[-1]:
... |
"""
你将得到一个字符串数组 A。
每次移动都可以交换 S 的任意两个偶数下标的字符或任意两个奇数下标的字符。
如果经过任意次数的移动,S == T,那么两个字符串 S 和 T 是 特殊等价 的。
例如,S = "zzxy" 和 T = "xyzz" 是一对特殊等价字符串,因为可以先交换 S[0] 和 S[2],然后交换 S[1] 和 S[3],使得 "zzxy" -> "xzzy" -> "xyzz" 。
现在规定,A 的 一组特殊等价字符串 就是 A 的一个同时满足下述条件的非空子集:
该组中的每一对字符串都是 特殊等价 的
该组字符串已经涵盖了该类别中的所有特殊等价字符串,容量达到理论上的最大值(也就是说,如果一个... |
"""
给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
示例 1:
输入:[[1,1,0],[1,0,1],[0,0,0]]
输出:[[1,0,0],[0,1,0],[1,1,1]]
解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
"""
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.