text stringlengths 37 1.41M |
|---|
our_list = [1,2,3,4,5]
jackson = ['a','b','c',1,2,3,'do','re','mi',True,False]
print(len(jackson))
print(jackson[4])
print(jackson[-4])
print(jackson[3:6])
print(jackson[:len(jackson):2])
print(jackson[::3])
print(jackson[::-1])
# embedded lists
emb_list = [1,2,3,[4,5,6],7,8,9]
print(emb_list[3])
print(emb_list[3... |
def bubble(arr):
for i in range(0,len(arr)):
for j in range(0,len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print arr
bubble([6,5,4,3,2,1])
|
for i in range (0,11): #declare counter and set range
if i % 2 == 0: #condition statement: is even if reminder of i/2 is zero
print i #what to do if condition is satisfied
for i in range (5,51): #declare counter and set range
if i % 5 == 0: #condition statement:... |
#Inheritance and composition
#The question of "inheritance versus composition" comes down to an attempt to solve the problem of reusable code. You don't want the duplicated code all over your codebase since it is neither clean nor efficient. Inheritance solves this problem by creating a mechanism for you to have impli... |
#declare a class with class className (parameter):
class User(object):
pass
#the parameter object means that class User inherits from object class.
#we can make instances --objects-- of this class:
helen = User()
mikel = User()
#think of class as blueprint and objects as versions of the blueprint
#classes inc... |
def change(cents):
coins = {
'dollar': 1,
'quarter': 0.25,
'dime': 0.1,
'nickel': 0.05,
'penny': 0.01
}
#dollars = 0
#quarters = 0
#dimes = 0
#nickels = 0
#pennies = 0
if cents > coins['dollar']:
dollars = (int(cents/coins['dollar']))
... |
# placing an asterisk before a parameter name means the variable will be passed a number of arguments
def varargs1(arg1, *others):
print "Got "+arg1+" and "+", ".join(others)
varargs1("one")
varargs1("one, two")
varargs1("one, two, three")
# what * does is join the rest of the arguments into a tuple
def varar... |
#DICTIONARIES
#Recap: lists are [a,b,c] tuples are (a,b,c)
#dictionaries are { "key":"value", "key":"value" }
#keys must be unique
#creating dictionaries:
#a) literal notation:
weekend = {"Sun": "Sunday", "Sat": "Saturday"}
#b) create an empty dictionary then add values:
capitals = {}
capitals["svk"] = "Brati... |
#create a class
class Person(object):
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
self.health = 100
self.stealth = 10
def introduce(self):
print "hello, my name is {}".format(self.name)
def display(self):
... |
# you can override parent behavior by defining it at the child level and there will not be a conflict:
class Parent(object):
def hobbies(self):
print "Watching TV"
class Child(Parent):
def hobbies(self):
print "Coding"
bob = Parent()
ren = Child()
bob.hobbies()
ren.hobbies()
# polymorph... |
# list comprehensions combine for loops, if statements, and variables to create lists
# syntax:
# [[element] [for [element] in [list]] [optional condition]]
# create a list of all even numbers from 0 t0 100
# element = each number; list = range(1,101); condition = if statement
even_numbers = [x for x in range(1,... |
# with is the preferred method for writing files instead of the traditional one
# traditional
myfile = open("file.txt", "w")
myfile.write("Hello again!")
myfile.close()
# with
with open("file2.txt", "w") as myfile2:
myfile2.write("Hi there!")
# no need to close |
well = -20
jump = 3
down = -2
day = 1
while well < 0:
print(day)
well += jump
if well >= 0:
break
well += down
if well >= 0:
break
day += 1
|
fraction = input("请输入您的分数:")
fraction = int(fraction)
if fraction >= 90 & fraction >= 100:
print("优秀!")
elif fraction >= 80 & fraction <= 90:
print("良好!")
elif fraction >= 70 & fraction <= 80:
print("一般!")
elif fraction >= 60 & fraction <= 70:
print("及格!")
elif fraction >= 0 & fraction <= 60:
print... |
# 1、定义厨师类,有姓名和年龄的属性,且属性私有化,提供相应的getXxx与setXxx方法,提供无返回值的无参数的蒸饭方法;
# 2、定义厨师的子类,该类中要求只能写一个无返回值的无参数的炒菜的方法,其他的方法不能写;
# 3、定义厨师的子类的子类,重写所有父类的方法,每个方法的内容只需打印一句话描述方法的功能即可;
# 4、定义测试类,创建厨师的子类的子类(厨师的孙子类)对象,使用该对象,对厨师类中的姓名和年龄属性赋值,并获取赋值后的属性值打印到控制台上;
# 5、使用厨师的孙子类对象调用该对象除了getXxx与setXxx以外的其他方法;
class Chef:
__name = ""
__age = 0
... |
class People:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def show(self):
print(self.name, self.age, self.sex)
class Work(People):
pass
class Student(Work):
def __init__(self, name, age, sex, num):
super().__init__(name... |
num1 = 1
name1 = "苹果"
price1 = 2
Quantity1 = 30
quality1 = "A+"
Origin1 = "山东"
print("-----------------------------------------------")
print("----------------欢迎来到水果商城系统--------------")
print("-----------------------------------------------")
print("编号 名称 价格 数量 质量 产地 ")
print(num1, name1, ... |
#base class
class user:
def __init__(self, fname, lname):
self.__fname = fname
self.__lname = lname
def get_full_name(self):
return self.__fname + " " + self.__lname
def login(self, username):
print("Authentication sucessfull")
def do_work(self):
print(self.__f... |
name = "George"
print("Hello %s" %name) # %s - for string
age = 30
print("You are %d years old!" %age) # %d - for integers
pi = 3.14
print("Value of Pi - %f" %pi) # %f - for floating point values
print("Hello %s, you are %d years old!!" %(name, age)) # multiple variables
user = ["Sara", 21, "IT"]
print("Hello %s, Y... |
# iterate till 10
for x in range(10):
print(x)
print("------------------------")
# specify start range
for x in range(4, 10):
print(x)
print("------------------------")
#increment by 2
for x in range(5, 20, 2):
print(x)
print("------------------------")
#else in for loop. will be executed at the end o... |
import math
while True:
while True:
try:
n1=float(input('Input Number 1'))
except ValueError:
print("Please, enter a valid number")
break
while True:
operation=input('Input operation')
if operation != "+" and operation !="-" and operation != "*" and operation != "/" and operation !="... |
class Solution:
# @param x, an integer
# @return an integer
def sqrt(self, x):
#binary search method
low = 0
high = x/2
val = 0
while low <= high:
val = (low + high)/2
print val
if val*val > x:
high = val - 1
... |
#!/usr/lib/python/
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if not head:
return head
... |
#!/usr/lib/python/
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
#binary search column first
#binary search row second
crst = self.binary_search_interval(matrix, target... |
#!/usr/bin/python
import pdb
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def inorderTraversalRecursive(self, root, rst =... |
#!/usr/lib/python/
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
#use back track to slove this method
return self.climbs(n, 0)
def climbs(self, n, subrst):
if subrst == n:
return 1
if subr... |
#!/usr/lib/python/
class Solution:
# @param matrix, a list of lists of integers
# @return a list of lists of integers
def rotate(self, matrix):
dim = len(matrix)
#transpose matrix
for i in xrange(dim):
for j in xrange(i, dim):
matrix[i][j], matri... |
import pdb
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {integer[]} inorder
# @param {integer[]} postorder
# @return {TreeNode}
def buildTreeRecursive(self, inorder, ... |
class Solution:
# @return a boolean
def isMatch(self, s, p):
#using dynamic programming to solve this problem
#f[i][j] denote isMatch up to word i, re j
# if p == '.' or p == s: if f[i-1][j-1] == 1
# if p == '*': if f[i][j-1] == 1: f[i][j] == 1 elif f[i][j-2] == 1: f[i][j] = 1
... |
#Create an object called Player
class Player:
#Initialize the variables.
def __init__(self, Health, Strength, Defense, Magic, Resistance):
self.Health = Health
self.Strength = Strength
self.Defense = Defense
self.Magic = Magic
self.Resistance = Resistance
#Break ... |
def file_data_open():
with open('recipes.txt', encoding='utf-8') as f:
counter = 0
ingridient_s = list()
cook_book = dict()
dish = ''
for line in f: # Проходимся по строке в файле
line = line.rstrip()
counter += 1
if counter == 1: # Перва... |
#!/usr/bin/python3
"""
this function count the number of lines
"""
def number_of_lines(filename=""):
'count the lines of the txt'
counter = 0
with open(filename, encoding='utf-8') as text:
for line in text:
counter += 1
return(counter)
|
#!/usr/bin/python3
"""
write a file
"""
def write_file(filename="", text=""):
'this function write in a text file'
with open(filename, mode='w', encoding='utf-8')as f:
w = f.write(text)
return(w)
|
#!/usr/bin/python3
def uppercase(str):
for c in str:
a = ord(c)
if c > '`' and c < '{':
a = a - 32
print('{}'.format(chr(a)), end="")
print("")
|
# Using the display function allows to show data frames as html even it's not the last entry (using print looks ugly)
# Your code does not need to contain the display()-wrapper
from IPython.display import display
# Load
data = pd.read_csv("./Ex02_01_Data.csv")
# Show structure
display(data.info())
# Show basic stats... |
# Add 5 to number
add5 = lambda n : n + 5
print(add5(2))
print(add5(7))
print()
# Square number
sqr = lambda n : n * n
print(sqr(2))
print(sqr(7))
print()
# Next integer
nextInt = lambda n : int(n) + 1
print(nextInt(2.7))
print(nextInt(7.2))
print()
# Previous integer of half
prevInt = lambda n : int(n // 2)
print(p... |
"""General math helpers."""
from __future__ import annotations
from collections.abc import Callable
import numpy
def sign(x: float) -> float:
"""Return the sign of the argument. Zero returns zero."""
if x > 0:
return 1.0
elif x < 0:
return -1.0
else:
return 0.0
def heavisid... |
"""A simple module for storing unit conversion factors to convert to SI.
Example: A length e.g. can be represented as 1.0 * unit.ft to represent one foot,
which will return 0.3048 meters.
"""
import math
# Acceleration due to gravity
_gravity = 9.80665
# Convert length to m
m = 1.0
cm = m / 100.0
mm = m / 1000.... |
# Day 10 problem
from collections import defaultdict
# First part
joltages = []
with open("textfiles/problem10.txt") as fp:
for jolt in fp:
joltages.append(int(jolt))
one_diff = 0
three_diff = 0
joltages.sort()
for i in range(len(joltages) - 1):
diff = abs(joltages[i] - joltages[i + 1])
if diff ==... |
# Created April 1st, 2018 (Happy April Fools - No easter eggs here sorry, maybe next time)
# Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them.
def is_prime(n):
""" Returns whether a number is prime or not using modulus """
# range(<# Inclusive ... |
import json
import random
import tkinter as tk
from tkinter import filedialog
from tkinter.font import Font
class LabyrinthGUI(tk.Frame):
"""
This class defines the main window look and feel.
"""
def __init__(self, root, labyrinth, agent):
"""
Creates a window that will show a visuali... |
import numpy as np
import sympy as sy
#Your optional code here
#You can import some modules or create additional functions
# DO NOT CHANGE THE NAME OF gausslegendre() function
def gausslegendre(f, a, b, n=20):
ans = 0
x,w = np.polynomial.legendre.leggauss(n);
i=0
#case 1
if(a==-1 & b==1):
... |
def isPrime(n):
c=0
for i in range(2,n):
if n%i==0:
c=c+1
if c==0 and n!=1:
return 1
else:
return 0
def sum(a,b):
'''
Adds to numbers
input: a, b - two numbers
output: returns sum
'''
c=a+b
return c
def div(a,b)
divide two numbers
input: a,b - two nu... |
"""
The purpose of this code is to explore the use of relaxation and over-
relaxation method on computing non-linear equations i.e. f(x) = x.
"""
import numpy as np
import matplotlib.pyplot as plt
#Part a
#Text Exercise 6.10 a
#we can modify the number of loops to acheive different levels of accuracy
#in our case we a... |
import random
import math
import string
scale = 1
#this is used to scale the end result, the larger the n, the larger the end shape is
number= 100
#this is used to set how many points we generate for each shape, the higher this is, the more points
def cylinder(scale,number):
cylinderlist = []
for item in range(num... |
import csv
import numpy as np
from matplotlib import pyplot as plt
def main():
Question1()
Question2()
Question3()
def Question1():
print("Question 1 Start -------------------")
N = 10
X = np.array([[-2],
[-5],
[-3],
[0],... |
# Creating line y=x+2 and seperating the points.
#Taking arbitrary point a,b and plotting left or right side
import numpy as np
import matplotlib .pyplot as plt
N = 50
x = 50*np.random.rand(N)
y = 2 +50* np.random.rand(N)
plt.scatter(x,y,) # (x co-ordi,y co-ordi,size,area,alpha)
plt.plot(x,x+2,color='blue',linewidt... |
"""
Basic functional utilities.
"""
def readLines(fileName):
"""
Return list of lines from the file.
"""
try:
f = open(fileName, 'r')
lines = [line for line in f]
f.close()
newlines = []
for line in lines:
if (len(line.strip()) != 0):
... |
#Escreva um programa que leia 10 notas e mostre na tela a média dos alunos
#e a quantidade de alunos que tiveram nota inferior a 6.
n=0
nota = 0
rep = 0
for i in range(0,10):
n = float(input("Informe a nota do aluno \n"))
nota += n
if n < 6:
rep+=1
media = nota/10
print("A média das notas é:" ,... |
#Uma empresa fez uma pesquisa de mercado para saber se
#as pessoas gostaram ou não de um novo produto lançado no mercado.
#Para isso, forneceu o sexo do entrevistado
#e sua resposta (S – sim ou N – não).
#Sabe-se que foram entrevistadas dez pessoas.
#Faça um programa que calcule e mostre:
#O número de pessoas que res... |
#A prefeitura de uma cidade fez uma pesquisa entre 10 habitantes, coletando dados sobre o salário e o número de filhos, armazene os salários e número de filhos em listas. Faça um programa que calcule e mostre:
#◦média de salário da população;
#◦média do número de filhos;
#◦maior salário;
#◦percentual de pessoas com sal... |
def collazt(number):
if number == 1:
print('collazt function complete')
elif number % 2 == 0:
print(number // 2)
return collazt(number // 2)
else:
print(3*number+1)
return collazt(3*number+1)
#print('Enter number :')
#number = int(input())
#collazt(numbe... |
import numpy as np
from scipy.integrate import ode
from .name2idx import C, V
from .set_model import DifferentialEquation
observables = [
]
class NumericalSimulation(DifferentialEquation):
""" Simulate a model using scipy.integrate.ode
Attributes
----------
normalization : bool
if True... |
def factorio(num):
sum = 1
for i in range(1, num+1):
sum = sum*i
print(sum)
factorio(3)
|
a = int(input("enter a number :"))
b = int(input("enter another number :"))
if a > b :
print("the bigger number is :", a)
else:
print("the bigger number is", b) |
x1 = int(input("enter no:"))
x2 = int(input("enter no:"))
x3 = int(input("enter no:"))
x4 = int(input("enter no:"))
x5 = int(input("enter no:"))
sum = x1+x2+x3+x4+x5
print("Sum is :" ,sum)
Average = sum/5
print("Average is:", Average)
|
# По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки.
x = float(input('Введите точку x <<<'))
y = float(input('Введите точку y <<<'))
k = round(y / x, 2)
print(f'y = {k}x + {y}')
|
def dfs(v):
print(v,end=" ")
visit[v] = 1
for i in range(1, n+1):
if visit[i] == 0 and matrix[v][i] == 1:
dfs(i)
def bfs(v):
queue = [v]
visit[v] = 1
while(queue):
v = queue[0]
print(v, end=' ')
del queue[0]
for i in range(1, n+1):
... |
def main_with_division(nums):
'''
This method involves the use of division. If we evaluate the product of an entire list of numbers, we will have: product = a*b*c. Using this, we can evaluate the result at i by dividing the index we are currently at. This results in the following: product = (a*b*c)/a = b*c.
... |
# -*- coding: utf-8 -*-
def print_two(*args):
arg1,arg2 = args
print "arg1: %r, arg2: %r " % (arg1,arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r " % (arg1, arg2)
def print_one(arg1):
print "arg1: %r " % arg1
def print_none():
print "none arg"
print_two("L","Q")
print_two_aga... |
import pygame
class LR_Endzone(pygame.sprite.Sprite):
'''This class defines the sprite for the left and right end zones'''
def __init__(self,screen,x_position):
'''This initializer takes a screen surface, and x position as
parameters'''
#Call the parent __init__() method
... |
import tkinter as tk
from tkinter.ttk import *
class App(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self.master = master
self.label_frame = tk.Frame(self.master)
self.label_frame.grid()
self.label... |
"""
Defines greetings inputs and responses
"""
import random
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up", "hey", "good morning")
GREETING_RESPONSES = ["Hello, Sir", "Greetings, Human.",]
def greeting(sentence):
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
... |
class DHeap:
"""D-nary min/max heap
Attributes:
__d: indicates how many children for a parent.
__isMaxHeap: indicates it's min or max heap.
__list: the structure that stores the data.
"""
def __init__(self, isMaxHeap=False, d=2):
"""Initializes the heap object, with def... |
def swapAlternate(a, n) :
i = 0
while i < (n-1) :
a[i], a[i+1] = a[i+1], a[i]
i += 2
# Driver
T = int(input())
for _ in range(T):
N = int(input())
arr = list(map(int, input().split()))
swapAlternate(arr, N)
print(*arr, sep=" ") |
# O(n^2) time | O(1) space
def insertionSort(arr, N):
for i in range(1, N):
curr = i
j = i-1
while j >= 0 and arr[curr] < arr[j]:
arr[curr], arr[j] = arr[j], arr[curr]
curr -= 1
j -= 1
# Driver
arr = [2, 3, 1, 0, 5, -1, 6, 10, 8, 7]
insertionSort(arr, le... |
def reverse(a):
i = 0
j = len(a) - 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
# Driver
arr = list(map(int, input().split()))
reverse(arr)
print(*arr)
# print(a[::-1])
|
parrot = "Norwegian Blue"
# print('using indexs.... def has to be an easier way to do this')
# print(parrot)
# print(parrot[3])
# print(parrot[4])
# print()
# print(parrot[3])
# print(parrot[6])
# print(parrot[8])
# print('using negative indexs')
# print(parrot[-11])
# print(parrot[-1])
# print()
# print(parrot[-11... |
#-*- coding:utf-8 -*-
class Animal(object):
def __init__(self, name, sex):
self.name = name
self.sex = sex
print 'created instance for:',self.name
def run(self):
print 'Animal is running...'
class Dog(Animal):
#重写__init__不会自动调用基类的__init__
def __init__(self,name,sex,kind... |
"""
This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well
as testing instructions are located at http://amzn.to/1LzFrj6
For additional samples, visit the Alexa Skills Kit Getting Started guide at
http://amzn.... |
import pygame
import random
import colors
# This class represents the ball
# It derives from the "Sprite" class in Pygame
blockHeight = 15
blockWidth = 20
class Block(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, color, width, height)... |
from random import randint
game = {
"R": 1,
"S": 2,
"P": 3
}
print("Let's Play A Rock-Scissor-Paper Game")
n = int(input("How many times you want to play this game = "))
for i in range(1, n+1):
print("Press R for ROCK , S for SCISSOR ,P for Paper")
z = game.get(input("R/S/P : ").upper())
y ... |
import math
def triangle():
'''
Pascal triangle generator
'''
n = 0
prev_row = [1]
yield prev_row
n += 1
prev_row = [1, 1]
yield prev_row
while True:
n += 1
row = [1]
for i in range(1, n):
row.append(prev_row[i-1]+prev_row[i])
row.app... |
"""
title: common functions for the unit
author: Jackson Reid
date-created: 2021-02-03
"""
import random, statistics, time
def getAverage(LIST):
return statistics.mean(LIST)
def getTime():
return time.perf_counter()
def getSimpleList():
return [1, 5, 3, 19, 11, 17, 7, 13]
def getLongList(SIZE):
... |
"""
Program: my_definitions.py
Author: Daniel Meeker
Date: 6/29/2020
This program defines a module with 4 functions in it
then imports the module into the testing file and calls
the functions.
"""
def welcome(name):
"""
This function is used to print a greeting
:param name: Name that is being welcomed
... |
import numpy as np
from math import sqrt
def square_root(val, tol=1e-4):
""" This is a docstring. Here I would explain what the square_root() function does. (It calculates the square root. Duh.)
:param a: The value whose square root you want to calculate.
:type a: float
:param tol: The tolerance of th... |
# Lab 1, Part 1: Naive Bayesian Classifier
# Yuan Hong Sun
# 1003039838
import os.path
import numpy as np
import matplotlib.pyplot as plt
import util
import itertools
import math
def learn_distributions(file_lists_by_category):
"""
Estimate the parameters p_d, and q_d from the training set
Input
... |
import os
import generator
"""Holds the "meat" for all the writing, reading, and generating"""
class CRC:
"""
Implemented as a way to shorten arguments, and because I thought it
was a smart idea at the time. Seems a little dumb now, but I might change it
"""
def __init__(self, crclist):
self.first= crclist[0... |
# first turtle
import turtle
# importing all from turtle.
pen = turtle.Turtle()
turtle.title("Heart Shape")
# some functions with turtle.
pen.color('red')
pen.begin_fill()
pen.left(140)
pen.forward(180)
#pen.stamp()
pen.circle(-90, 200)
#pen.stamp()
pen.setheading(60)
#pen.stamp()
pen.circle(-90, 20... |
# Author: Spencer Mae-Croft
# Date: 08/31/2020
# Testing modularity of python
def make_pizza(size, *toppings):
"""Summarize the pizza that is about to be made"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings: ")
for topping in toppings:
print("- " + topping)
... |
#encoding: UTF-8
#Autor: Rodrigo Rivera Salinas A01375000
#Descripcion: Calcular el rendimiento de un automovil a partir de la gasolina dada y los km dados
def gasyL(kilometros,litros): #se va a dividir los km y los litros y se van a guardar
gaseL=kilometros/litros
return gaseL
def millas(kilometros): ... |
#FamilyTree
#Majority of code taken from http://rosettacode.org/wiki/Tree_traversal#Python and editted
#to use as an example for unit testing.
__author__ = "Angel Dixon"
from collections import namedtuple
from sys import stdout
Node = namedtuple('Node', 'data, left, right')
tree = Node('Grandma',
Node... |
import random
def matrix_add(a, b):
""" Add two matrices """
m = [[0 for j in range(len(a[0]))] for i in range(len(a))]
for row_index, i in enumerate(a):
for col_index, j in enumerate(i):
m[row_index][col_index] = a[row_index][col_index] + b[row_index][col_index]
return m
def mat... |
"""Creation and maintenance of Red-Black Trees"""
class RBTree:
"""
A Red-Black tree.
"""
def __init__(self):
"""
Initialize tree with root as universal NIL node.
"""
self.nil = Node("B", None, None, None, None)
self.root = self.nil
def __repr__(self):
... |
import nltk
import string
import re
def remove_punct(text):
text_nopunct = "".join([char for char in text if char not in string.punctuation])
return text_nopunct
def tokenize(text):
tokens = re.split('\W+', text)
return tokens
def remove_stopwords(tokenized_list):
stopword = nltk.cor... |
def isPrime(test_prime):
num = 3
while True:
num += 2
if num > (test_prime / num):
break
if (test_prime % num) == 0:
return False
return True
test_prime_factor = 600851475143
max_factor = 0
num = 3
while True:
num += 2
if num > (test_prime_factor / ... |
# This script is writed for remind me some tips about how to use string object in Python
import os
def clear():
os.system('clear')
os.system('cls')
newLine = "\n"
def frame (param):
print(newLine)
print('|------------------------------------------------------------|' + newLine)
print('| ... |
# Unit2: lesson 1 - calculating summary statistics on a pandas dataframe
from scipy import stats
import pandas as pd
data = '''Region, Alcohol, Tobacco
North, 6.47, 4.03
Yorkshire, 6.13, 3.76
Northeast, 6.19, 3.77
East Midlands, 4.89, 3.34
West Midlands, 5.63, 3.47
East Anglia, 4.52, 2.92
Southeast, 5.89, 3.20
Southw... |
# -*- coding:utf8 -*-
"""
关键字封装(selenium二次封装)
达到跟RF一样的效果(main函数中调用时)
即开源自动化测试框架
"""
from selenium import webdriver
from time import sleep
class TestKeywords(object):
#初始化
def __init__(self, url, browsertype):
self.driver = self.open_browser(browsertype)
self.driver.get(url)
#调用浏览器
def... |
#1 to n numbers
def print1(n):
if n==0:
return
print(n,end=" ")
print1(n-1)
print1(10)
print("\n")
#n to 1 numbers(reverse order)
def print2(n):
if n==0:
return
print2(n-1)
print(n, end=" ")
print2(10)
|
valor2 = int(input("Valor :"))
if(valor2 > 5):
print ("valor maior que 5")
else:
print("Valor menor que 5") |
from collections import deque
def find_target(values, target):
dq = deque(sorted([(val,idx) for idx, val in enumerate(values)]))
print(dq)
while True:
if len(dq)< 2:
raise ValueError("No match Found")
val_sum = dq[0][0]+dq[-1][0]
if val_sum > target:... |
# 1. generate random number
# 2. print the random number
from random import randint
print(randint(1, 10)) |
import re
b = '会议地点: Guimarães, Portugal'
a = re.findall(r'会议地点: (.*)', b)
print(a) |
import math
import random
import tkinter as tk
# The different levels to correspond to the different levels of difficulty
# of the sums that are given
def P1():
global y
global x
global answer
global question
global valid
y = 0
x = 1
while (y < x): #Random number generator t... |
"""
All NLG methods and an interface to select between them.
:author: Derek S. Prijatelj
"""
import os
import csv
import random
import numpy as np
import pandas as pd
import markovify
import sys
def frequency(sentence_length, frequencies=None, lang='en', filepath=None):
"""
Basic word frequency NLG method.
... |
# Разложение на произведение простых чисел и их показатель
# Prime Factorization
def factorize(num):
"""
num -> prime factors
"""
factor = 2
prime_factors = ""
factors = []
exp = []
while num != 1:
if num % factor == 0:
if factors and factors[len(factors) - 1] != ... |
# Вычисляет расстояние между двумя городами и позволяет пользователю выбрать размерность расстояния.
# Эта программа может потребовать информацию о городах, такую как долготу и широту.
# Use latitude and longitude of two cities to calculate a distance between them
import numpy as np
from geopy.geocoders import Nomina... |
# Sort the odd
# You have an array of numbers.
# Your task is to sort ascending odd numbers but even numbers must be on their places.
#
# Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
#
# Example
#
# sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
def ... |
# Счётчик слов
# Count Words
class WordCounter:
def __init__(self):
self.words = 0
self.data = None
def countWords(self, string=None, file=None):
"""
:param string: - If user wants to work with string
:param file: - If user wants to work with file
:return: - W... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.