text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
""" Script used to tabify a file - replace group of spaces with a tab """
import shutil
import os
import re
import sys
# import argparse
re_line_beginning = re.compile(r'^[ \t]+')
re_is_comment = re.compile(r'\s*[!#*/].*')
re_spaces = re.compile(r'^[ ]')
TAB = '\t'
SPACE = ' '
def is_comment_... |
from tkinter import *
import os
win = Tk()
win.title("Shutdown And Restart")
win.geometry("270x60")
def shutdown():
os.system("shutdown /s /t l")
def restart():
os.system("shutdown /r /t l")
button1 = Button(win,text="Shutdown",command=shutdown,height=3,width=17)
button1.grid(row=0,column=0)
button2 = Bu... |
# coding: utf-8
'''
@name: 二叉链表
@author: Ivanli
@time: 2018/01/05
'''
class BitNode(object):
'''
结点类
'''
def __init__(self, data=-1):
self.data = data # 结点数据
self.lchild = None # 左孩子指针
self.rchild = None # 右孩子指针
def __repr__(self):
return str(self.data)... |
class Filter(object):
'''
过滤掉s中t以外的子字符串
'''
def __init__(self, s, t):
self.s = s
self.t = t
self.s_len = len(s)
self.t_len = len(t)
self.res = ""
def filter(self):
'''
1、将s看做一个个长度t长度的子字符串,分别跟t比较,若不等,则把当前s字符串起始的字符扔进结果里
2、否则,下标移动t个长度(因为这... |
# coding: utf-8
'''
@class: 队列的循环顺序存储结构
@author: Ivanli
@time: 2017.12.26
'''
class CircularOrderQueue(object):
def __init__(self, maxsize):
self.front = 0
self.rear = 0
self.maxsize = maxsize
self.queue = []
for i in range(self.maxsize):
self.queue.append(Non... |
# coding: utf-8
class BiTNode(object):
'''
二叉树的二叉链表结点
'''
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
class BST(object):
'''
二叉排序树(二叉查找树)
'''
def __init__(self):
self.curNode = None # 当前结点
self.root = None ... |
#! /usr/bin/python2.5 -tt
# Problem Set 2
# Name: Anna Liu
# Collaborators: N/A
# Time: 00:20:00
# Date: 29/03/2014
# search and print the largest number of McNuggets
# that cannot be bought in combination of "box_size"
#incorrect: doesn't work for cases like (x, 2x, 3x)
box_size = (6, 9, 20)
top_lim = 200
def mai... |
wish_list = ["iceland", "alaska", "kenya", "artic", "galapagos"]
#printing original list
print(wish_list)
print("\n")
#printing sorted wish list (temporarily)
sorted(wish_list)
print (sorted(wish_list))
print ("\n")
print(wish_list) #still an original list
#printing sorted wish list (temporarily) reverse
wish_list =... |
guest_list = ['ada lovelace', 'steve w', 'eric', 'jay', 'oprah', 'arnold', 'the rock']
print(guest_list)
guest_who_cant_make_it =guest_list[0]
guest_list[0] = 'Matthew'
print(guest_list)
print ("There is one guest who can't make it, her name is " + guest_who_cant_make_it + ".")
i=0
while i < len(guest_list):
print(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 13:34:17 2018
@author: dvalput
"""
import numpy as np
def normalize_by_columns_maxmin(X, y):
# X - matrix of training examples
# y - vector of targets
# Normalizes by using the maximum value in each column
X_norm = np.e... |
# James Jack
# 2/13/21
# program draws polygon based on user input
import turtle # loads graphics program
wn = turtle.Screen() # creates screen
james = turtle.Turtle() # names turtle
sides = int(input("how many sides?"))
length = int(input("how long is the side?"))
color = input("what color are the l... |
# -*- coding: cp1252 -*-
import time
def printStuff(intVar,strVar,floatVar):
#4. Use the print function and .format() notation to print out the variable you assigned
print("\nHi there, I've got some lovely variables here. Let's take a look:")
time.sleep(2)
print("\nFirst off, there's {}, which is quit... |
# Function to check if the set of parentheses, brackets, and braces is balanced or not
def checkSet(set):
stack = []
# Program will check for {, (, and [. Will determine if set is logical or not. Append pushes element
# to the top of the stack.
for sym in set:
if sym in ["{", "(", "["]:
... |
"""program"""
def cube_root(n_value):
"""function"""
v=int(n_value)
try:
if v > 0:
print(v**(1/3))
return v**(1/3)
elif v < 0:
print(-(-v)**(1/3))
return -(-v)**(1/3)
except TypeError:
res = "enter only numbers"
return ... |
# 1.基本数据类型
a = 7
b = 3.14
c = False
d = 1 + 2j
str = "hello python"
print(a)
print(b)
print(c)
print(d)
# 2.查看数据类型
print(type(a))
print(type(b))
print(type(c))
print(type(d))
# 3.多行语句
str = "中国广东" \
"深圳南山" \
"软件产业基地"
print(str)
# 在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)
fruits = ["apple"... |
# 1.python运算符
print("1+2=%d" % (1 + 2))
print("1-2=%d" % (1 - 2))
print("1*2=%d" % (1 * 2))
print("6/2=%d" % (6 / 2))
print("9//2=%d" % (9 // 2)) # 整除
print("9除以2=%d" % (9 % 2)) # 整除
print("2的4次方=%d" % (2 ** 4)) # 2*2*2*2=16
print((1 + 2) * 3)
# 2.python定义变量
age = 12
height, weight, name = 170, 130, "小明... |
"""
猜拳游戏使用ifelse代码实现
0为石头,1位剪刀,2为布
"""
import random
while True:
wanjia = int(input("请玩家出拳,0为石头,1为剪刀,2为布:"))
diannao = random.randint(0, 2)
print("diannao: %d" % diannao)
# 玩家获胜判断
if (wanjia == 0 and diannao == 1) or (wanjia == 1 and diannao == 2) or (wanjia == 2 and diannao == 0):
... |
# 1.指定utf-8格式写文件
# 写文件
file = open("./file/test.txt", "w", encoding="utf-8")
# 写文件
file.write("Python 很好玩,可以爬你喜欢的妹子图片...")
# 关闭文件流
file.close()
# 2.不需要关闭流
with open("./file/test1.txt", "w", encoding="utf-8") as f:
f.write("学习python还是有钱途的...")
# 3.不需要关闭流
import codecs
with codecs.open("./file/... |
'''
List列表
这个是python里面用的最多最常用的数据类型,可以通过下标来访问,可以理解为java或者c里面的数组.
但是功能比数组强大n倍,list可以放任意数量的python对象,可以是字符串,字符,整数,浮点等等都可以,
而且创建,添加,删除也很方便.
'''
# 1)创建list //list内部的对象可以是字符串,字符,数字,支持混搭
aList = ["apple", 100, 3.1415926, "banana", 'A', "B", "深圳", False, "orange"]
print(aList)
# 2)访问list //直接通过下标去访问
print("aList[3... |
# encoding=utf-8
from threading import Thread
from queue import Queue
import time
# 生产者
class Producer(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
global queue
count = 0
while True:
if queue.qsize() < 1000:
for ... |
# 元组与列表类似,不同之处在于元组的元素不能修改。
# 元组使用小括号,以逗号隔开,也是可以存储不同类型的数据,但是尽量存储同类型数据,列表使用方括号。
# 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
# 一、元组
languages = ("java", "c++", "shell", "lua", "java")
# 1.index() 查找数据对应的下标
index = languages.index("shell")
print("index = %d" % index)
# 2.count() 统计元素出现的次数
count = languages.count("java"... |
'''
Dictionary(字典)
字典(dictionary)是Python中另一个非常有用的内置数据类型。
列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。
键(key)必须使用不可变类型。
在同一个字典中,键(key)必须是唯一的。
'''
# 0.定义字典
# 构造函数 dict() 可以直接从键值对序列中构建字典
sourse = {}
sourse["one"] = "语文"
sourse[1] = "英语"
stu... |
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pinList = [17, 27, 22]
for i in pinList:
GPIO.setup(i, GPIO.OUT)
while(1):
x = input("Switch port: ")
if x == -1:
GPIO.cleanup()
print("GPIO Clean up")
break
else:
if x <= 3 and x > 0:
if GPIO.input(pinList[x-1]):
# High
GPIO.outp... |
# Simulations to verify probability calculations
import random
def three_geom_prob(p, k):
""" Pr(X + Y + Z <= k) where X, Y, Z are independent geometric distributions """
q = 1 - p
prob = 0
for i in range(1, k - 1):
inner_sum = 0
for j in range(1, k - i - 1):
inner_sum += p ... |
#!/usr/bin/env python3
import collections
import datetime
import json
Todo = collections.namedtuple('Todo', 'desc time status priority')
todos = dict()
def initialize():
'''This should run at the start of the program, it will look for a JSON file and
load it into a dict that contains a key as the descripter and... |
# -*- coding: utf-8 -*-
"""
Tools to deal with Word equations format
See Also
--------
if working with Word and Python, you may be interested in the python-docx
package although equations are not yet supported.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from .core impo... |
import sqlite3
def connect():
conn=sqlite3.connect("banco.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTs aluno (id INTEGER PRIMARY KEY , name TEXT , cpf TEXT)")
cur.execute(
"CREATE TABLE IF NOT EXISTs professor (id INTEGER PRIMARY KEY , name TEXT , cpf TEXT , departament... |
def add(x, y):
if type(x) != int or type(y) != int:
return None
else:
return x + y
def subtract(x, y):
if type(x) != int or type(y) != int:
return None
else:
return x - y
def divide(x, y):
if type(x) != int or type(y) != int:
return None
elif y == 0:
... |
# Variable 变量,提供了自动求导的功能
# Variable 和 Tensor本质上没有区别,Variable会被放入一个计算图中,然后进行前向传播,反向传播,自动求导。
# Variable 在torch.autograd.Variable中, 若要将tensor a 转换为Variable ,只用Variable(a)即可
# Variable有三个重要的组成属性,data,grad 和grad_fn
# data可以取出Variable里面的tensor数值
# grad_fn 小时的是得到Variable的操作
# grad是这个Variable反向传播的梯度
# 在单变量函数中,梯度可以理解为只是导数
# 函... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 10:31:12 2019
@author: ahenders
Advent of Code, 2019, Day 2
https://adventofcode.com/2019/day/2
(Intcode)
Here are the initial and final states of a few more small programs:
1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2... |
class Employ:
def __init__(self,empno, name, basic):
self.empno = empno
self.name = name
self.basic = basic
def __str__(self):
return "Empno %d Name %s Basic %d" %(self.empno,self.name,self.basic)
class Divya(Employ):
def __init__(self,empno,name,basic):
super().__in... |
class Employ:
def __init__(self, empno, name, sal):
self.empno = empno
self.name = name
self.sal = sal
def __str__(self):
return "Empno %d, Name %s, Salary %d " %(self.empno, self.name, self.sal)
emp = Employ(1, "Satish", 88555)
print(emp) |
a=int(input("Enter First Number "))
b=int(input("Enter Second Number"))
c=a+b
print('Sum of ',a, 'and ',b, ' is ',c) |
#coding=utf-8
from random import randint
global money
money = 100
print 'your money =',money
while money > 0:
stake = int(input('请下注:'))
a = randint(1, 6)
b = randint(1, 6)
print '你掷出的点数是',a + b
if a + b == 7 or a + b == 11:
money = money + stake
print 'you win!','you money =',money... |
idade_em_dias = int(input())
anos = 0
meses = 0
dias = 0
anos = idade_em_dias // 365
if anos >= 1:
idade_em_dias = idade_em_dias - (anos * 365)
meses = idade_em_dias // 30
if meses >= 1:
idade_em_dias = idade_em_dias - (meses * 30)
dias = idade_em_dias
print("{} ano(s)".format(anos))
pri... |
def timeConversion(s):
hhMMss = s.split(":")
if hhMMss[-1][-2:] == 'AM':
hour = int(hhMMss[0])
if hour >= 12:
return '0{}:{}:{}'.format(hour - 12, hhMMss[1], hhMMss[2][0:2])
elif hour >= 10:
return '{}:{}:{}'.format(hour, hhMMss[1], hhMMss[2][0:2])
return ... |
# coding=utf-8
"""
Blur the images with various low pass filters
详情参见 https://docs.opencv.org/3.1.0/d4/d13/tutorial_py_filtering.html
分类:
1. low-pass filters(LPF)
2. high-pass filters(HPF)
作用:
LPF helps in removing noises, blurring the images etc.
HPF filters helps in finding edges in the images.
image blur是通过低通滤波... |
# coding=utf-8
"""
画形状的要素:
line 直线 start end
rectangle 矩形 left-top bottom-right
circle 圆 original radius
ellipse 椭圆 original major_axis minor_axis angle(逆时针) start_angle(顺时针) end_angle
polygon 多边形 顶点
thickness : Thickness of the line or circle etc.
If -1 is passed for closed figures like circles,
it will fill the s... |
###
import numpy as np
import __builtin__
#import math
def compute_step(x, nn=None, log_flag=False):
"""
Compute the increasing step of an array x.
It is the average of the consecutive difference.
If log_flat set, it is the log of the ratio.
INPUTS
the array of values
... |
##
# A program for form validation of names, emails, passwords, and address's.
# Student Name: Will Malisch
# Student ID: wmalisch
# Student Number: 250846447
## Define the main function
# @param no parameter, just runs
#
def main():
# Import all the functions created in string validation
from strin... |
def add(a,b):
return a+b
def sub(a,b):
if a>b:
return a-b
elif b>a:
return b-a
else:
return 0
print("Module interpreter") |
import argparse
import csv
class CLI:
def read(self):
"""Initialize a command line interface"""
# Define arguments
parser = argparse.ArgumentParser(description='Analyze csv file and apply naive bayes')
parser.add_argument('-i','--input', nargs=1, help='CSV input file')
pars... |
import time
#function for finding the sum of the divisors of n
def sum_of_div(n):
s = 0
for num in range(1,int(n/2+1)):
if n % num == 0:
s = num + s
return s
t = time.clock()
d = dict()
for num in range(1,10000):
sum = sum_of_div(num)
if (num in d):
continue
e... |
"""
PONG
Written by Mayur Saxena
Written for Mr. Reid
ICS3U, Culminating Project
Date Started: December 3, 2012
Date Completed: December 10, 2012
This is a Pong game, with 1 player and 2 player modes.
It also has a highscore feature.
Program is written in Python, using the pygame library.
"""
# Just as a note, every... |
"""
CP1404/CP5632 Practical - Suggested Solution
Hexadecimal colour lookup
"""
COLOUR_CODES = {"DarkSalmon": "#E9967A", "DarkKhaki": "#BDB76B",
"Fuchsia": "#FF00FF", "SlateBlue": "#6A5ACD",
"MediumSpringGreen": "#00FA9A", "MediumAquamarine": "#66CDAA",
"MediumSlateBlue":... |
def unqiue(listt):
i = 1
if listt == []:
return True
while (i < len(listt)):
if listt[0] == listt[i]:
return False
else:
i = i + 1
else:
return unqiue(listt[1:])
a = unqiue([1,2,3,6,4,5,6])
print a
|
def checkLegal(board, turn):
legal = True
#check nifu
for filen in range(9):
if [line[filen] for line in board].count("P")>1:
print "nifu for sente"
legal = False
if [line[filen] for line in board].count("p")>1:
print "nifu for gote"
legal = ... |
#QUESTÃO 11 - Elabore um algoritmo por meio de fluxograma que imprima os núm
# eros entre 0 e 20, em ordem descendente.
def num():
numeros=[i for i in range(21)]
print(f'{numeros[::-1]}')
num()
|
import time
from itertools import permutations
print("Anagram Solver Minimal - lighter algorithm than https://repl.it/@skuzzymiglet/Anagram-Solver-V2")
def list_confine(l, anagram):
# Effectively solves the anagram, no repeated reads needed!
return_list = []
for element in l:
if len(element) == le... |
import itertools
from itertools import permutations
words = open("words.txt", "r")
word_list = words.read().split()
def create_possibilities(word):
return list(permutations(list(word), len(word)))
def solve_anagram(anagram):
answers = []
for y in create_possibilities(anagram):
combin = map(''.j... |
import itertools, time
from itertools import permutations
print("Anagram Solver V2 - improved algorithm over https://repl.it/@skuzzymiglet/Anagram-Solver")
words = open("words.txt", "r")
word_list = words.read().split()
anagram = input("Anagram: ")
def create_possibilities(word):
return list(permutations(list(word)... |
import random
r = random.randint(0, 10)
chances = 0
guess = int( input ("Guess a number: "))
while chances < 3:
if guess == r:
print("Congrats, you were right")
if guess > r:
print("Nope, too high", r, guess)
guess = int( input("Guess a number: "))
if guess < r:
pr... |
'''
Small utility for generating a set of unique RGB values in the
world map. This list is used for keys in a lookup table.
'''
from PIL import Image
'''
Mode to generate the table in. Can be one of:
'rgb-to-biome' : Convert RGB values into biome room types.
'''
# Mapping of modes to various needed things... |
from queue import PriorityQueue
import pygame
import win32api
# defining color constants
WHITE = (255, 255, 255) # White Color Code
RED = (255, 0, 0) # Red Color Code
GREEN = (0, 255, 0) # Green Color Code
BLUE = (0, 0, 255) # Blue Color Code
BLACK = (0, 0, 0) # Black Color Code
PURPLE = (128, 0, 128) # Purple Color C... |
from collections import deque
def parens_balance_check(string):
stack = deque([])
starting_braces = { "(": ")", "{": "}", "[": "]"}
ending_braces = { ")": "(", "}": "{", "]": "["}
for i, _char in enumerate(string):
if _char in starting_braces:
stack.append(_char)
if _char... |
#https://www.interviewcake.com/question/recursive-string-permutations
def perm_recursive_string(characters):
if len(characters) == 2:
result = [characters[1], characters[0]]
return result
else:
first = characters[:1]
rest = characters[1:]
first.extend(perm_recursive_s... |
def reverse_list(ary):
last_value = ary.pop()
if len(ary) > 0: reverse_list(ary)
ary.insert(0, last_value)
# why did i fail the second time?
# I started from the first value when I needed to concentrate on the second value
def reverse_list_two(ary):
first_value = ary.pop(0)
if len(ary) > 0: rever... |
def detectDuplicates(ary):
value_counts = {}
for v in ary:
if v in value_counts:
value_counts[v] += 1
else:
value_counts[v] = 1
return value_counts
results = detectDuplicates([1,2,3,3,3,3,4,5,5,5,5,6])
print 'results: {0}'.format(results)
|
# Verifica se um número é ímpar (ou se é par)
# entrando com o valor de n
n = int(input("Digite o valor de n:"))
# indices e variaveis
num = n
# loop
while num > 0: # enquanto num for maior que zero
n = num % 2 # n recebe num modulo 2 (resto da divisao de num por 2)
if n != 0: # se n for diferente... |
"""
Retorna el valor numerico de la letra o caracter entregado
"""
def Valor_Num(caracter):
mayus = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
minus = "abcdefghijklmnopqrstuvwxyz"
if caracter in mayus:
valor = ord(caracter) - 29
elif caracter in minus:
valor = ord(caracter) - 87
elif... |
# 1 - Print all integers from 0 to 150.
for i in range(151):
print(i)
# 2 - Print all the multiples of 5 from 5 to 1,000
# ADJUSTED**
for i in range(5, 1001):
if i % 5 == 0:
print(i)
# More efficient way of executing #2.
for i in range(5, 1001, 5):
print(i)
# 3 - Print integers 1 to 100. If d... |
from chatterbot import ChatBot
chatBot = ChatBot(
"FeedBackFruits",
storage_adapter="chatterbot.adapters.storage.JsonFileStorageAdapter",
input_adapter="chatterbot.adapters.input.TerminalAdapter",
output_adapter="chatterbot.adapters.output.TerminalAdapter",
database="response_database.db",
logi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 19:53:56 2018
@author: aman
"""
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slope_and_intercept(x, y):... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = Node(root)
def inorder(self):
if self.root:
self._inorder(self.root)
def _inorder(self, curr):
if curr:
#no return statement here as you need to trav... |
'''
consider all cells to have True or False values - so following the cells
with True would eventually lead us to the end of the maze/solution?
Like a 2D list of False and True values
in main fn
- do some error checking
- call helper recursive function
in recursive fn
- base cases - when should my solution give me... |
def magic_index(arr):
return binary_search(0, len(arr) - 1, arr)
def binary_search(start, end, arr):
# base case
# positive - arr[mid] == mid
# negative - start reaches the end of the input
if start > end:
return -1
mid = (start + end) // 2
if arr[mid] == mid:
return mid... |
"""
3. Сформировать из введенного числа обратное по порядку входящих в него
цифр и вывести на экран. Например, если введено число 3486,
то надо вывести число 6843.
Подсказка:
На каждом шаге вам нужно 'доставать' из числа очередную цифру
Пока все числа не извлечены рекурсивные вызовы продолжаем
Условие заверше... |
# Operators are special symbols that helps to perform operations on operands(variables and values)
a = 20
b = 5
# Add two operands
print('a + b =', a+b) # Output: a + b = 25
# Subtract right operand from the left
print('a - b =', a-b) # Output: a - b = 15
# Multiply two operands
print('a * b =', a*b) # Output: a * b... |
class Deque(object):
def __init__(self):
self.items = []
def addFront(self, item):
self.items.append(item)
def addRear(self, item):
self.items.insert(0, item)
def removeFront(self):
self.items.pop()
def removeRear(self):
self.items.pop(0)
def printDe... |
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
... |
class Dog():
def __init__(self, breed, name):
self.breed = breed
self.name = name
#self to connect with the object, so the dog 'Lola' can bark :)
def bark(self, number):
print("Woof, my name is {} and the number is {}" .format(self.name, number))
myDog = Dog('Criollo', 'Lola')
my... |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup
from Today import Today
import urllib2, re, json
class ScraperSemcon():
def __init__(self):
name = 'Semcon'
url = "http://www.frontviewclub.se/guide.asp?PresentationId=11"
dishes = []
price = '... |
def solution(p_string):
prev_letter, max_letter = None, None
curr_len = 0
max_len = 0
for curr_letter in p_string:
print(prev_letter, curr_letter)
if prev_letter == curr_letter:
curr_len += 1
if curr_len > max_len:
max_len = curr_len
... |
#coding=utf-8
'''
Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive.
The string can contains any char.
'''
def xo(s):
count_x = 0
count_0 = 0
if isinstance(s,str):
for i in s:
if i == 'x' or i == 'X':
... |
#coding=utf-8
'''
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line.
Each of them has a single 100, 50 or 25 dollars bill. A "Avengers" ticket costs 25 dollars.
Vasya is currently working as a clerk. He wants to sell a ticket to every single pe... |
class Node:
"""
A simple node class. Can be used to create a tree-like structure.
"""
def __init__(self, data, children=None, root=False):
children = [] if not children else children
self._data = None
self._children = set()
self.set_data(data)
self.add_child(nodes=children)
self._parent = None
self._... |
On cree une variable qui vaut 5
boite = 5
#On stock les elements
if boite > 10 :
print("plus grand")
elif boite < 10 :
print("plus petit")
else:
print("egal")
#------------------
#exemple 2
#on garde le reste de la division de 52 par 2 (le modulo)
#On stock le résultat dans la variable boite
boite =... |
a = "+ "
b = "- "
c = "| "
d = " "
i = 0
def print_line1():
i = 0
print("")
while (i < 11):
if i % 5 == 0:
print (a, end = '')
else:
print(b, end = '')
i = i + 1
def print_line2():
i = 0
print("")
while (i < 11):
if i % 5 == 0:
... |
from trie import Trie
from data import *
from welcome import *
from hashmap import HashMap
from linkedlist import LinkedList
# Printing the Welcome Message
print_welcome()
# Write code to insert food types into a data structure here. The data is in data.py
# Inserting all the food type information into one Trie
orig... |
from tkinter import filedialog, END, INSERT;
class FileManager:
# Open the existing text file
def open_file(self, text):
# Open dialog and ask the user to select a file
existing_file = filedialog.askopenfile(filetypes=[('Text File', '.txt'), ('Python File', '.py')])
# Clear the existin... |
#Talents = ['Sing','Dance','Magic','Act','Flex','Code']
Talents = [1,2,3,4,5,6,7,8,9]
Candidates = ['A','B','C','D','E','F','G']
CandidateTalent = []
print("All talents is below")
print(Talents)
"""
for c in Candidates:
talent = list(map(int,input("Input "+c+" talent: ").split()))
CandidateTalent.append(talent... |
# This file sets the starting and finishing time of the program and creates directory names based on the date
import datetime
# This class is for getting the program executing time and define the file names and ...
class Set:
def __init__(self):
self.date_set = datetime.datetime.now() # Clocks the runnin... |
#this is homework for python1
#定义有参数的函数,下面函数的参数为必需参数
def have_arg(a):
b = a+1
#有返回值 返回值为b
return b
#定义无参数的函数
def no_arg():
print("this is no argument function")
#无返回值情况 默认返回值为None
return
print(have_arg(1))
#输出值为2
print(no_arg())
#输出值为“this is no argument”
# None |
print("Hello World")
name = "Pramod Kumar"
print("Hello", name)
print("Hello" + name)
num = 42
print("Hello", num)
print("Hello" + str(num))
food_one = "Pizza"
food_two = "Grilled Sammon"
print("I love to eat {} and {}".format(food_one,food_two))
print(f"I love to eat {food_one} and {food_two}")
import sys
print(sys... |
class User:
def __init__(self, username,email_address):
self.name = username
self.email = email_address
self.account_balance = 0
def make_deposit(self, deposit_amount):
self.account_balance += deposit_amount
def make_withdrawal(self,withdrawl_amount):
self.account_ba... |
# Return True if an integer is evenly divisible by 5, and False otherwise
def divisible_by_five(number):
return True if number % 5 == 0 else False
print(divisible_by_five(4456))
|
# Return True when num1 is equal to num2; otherwise return False.
def is_same_num(num1, num2):
return num1 == num2
print(is_same_num(8,5))
|
#!/usr/bin/env python3
# Created by: Matthew Meech
# Created on: Sep 2021
# This program Calculates 2 numbers being added
def main():
# input
number1 = int(input("Enter the frist number you would like to add : "))
number2 = int(input("Enter the second number you would like to add : "))
# process
... |
class Email:
def __init__(self, sender, receiver, content):
self.sender = sender
self.receiver = receiver
self.content = content
self.is_sent = False
def send(self):
self.is_sent = True
def get_info(self):
return f"{self.sender} says to {self.rece... |
def average(numbers):
return sum(numbers) / len(numbers)
def solve(employees_string, happiness_factor_string):
employees = list(map(int, employees_string.split(' ')))
employees_count = len(employees)
happiness_factor = int(happiness_factor_string)
employees = list(map(
lambda empl... |
#Using list to represent stack
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
#Using class to represent stack
class Stack:
def __init__(self):
self.items = []
def ... |
Lists:
Complexity
Operation | Example | Class | Notes
--------------+--------------+---------------+-------------------------------
Index | l[i] | O(1) |
Store | l[i] = 0 | O(1) |
Length | len(l) | O(1) |
A... |
import random
def swap(arr,a,b):
print "swapping %i and %i"%(a,b)
temp=arr[a]
arr[a]=arr[b]
arr[b]=temp
def randomPartition(arr,start,end):
swap(arr,start,random.randint(start,end))
partition(arr,start,end)
def partition(arr,start,end):
v=arr[start]
h=start
for i in range(sta... |
import sys
class Node:
def __init__(self,val,left,right):
self.val=val
self.left=left
self.right=right
def left(self):
return self.left
def right(self):
return self.right
def __str__(self):
return str(self.val)
nodes=[Node(i,None,None) for i in range(... |
import random
import string
import time
import turtle
class Game:
def createGame():
''' Creates a new tic-tac-toe game. Sets up a screen for output, a turtle, and an initial empty board state.'''
global boardState
boardState = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
... |
import csv
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import itertools
def Timecodes(input): #Input: filename für Zeit(gemittelt); Output: 2D-Liste mit nur Zeit
Tk().withdraw()
# Mittelwerte sind der Output aus LaRochelle Script. Positionen sind der Output aus Glasgow script, mit ... |
from nltk import word_tokenize , sent_tokenize
text = "Hello there, how are you? I am Mr.John. Python is awesome. It is definitely better than the Anaconda distribution!"
for sentence in sent_tokenize(text):
print "SENTENCE------------>",sentence
for word in word_tokenize(sentence):
print word
# stop words - ... |
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LinearRegression
... |
import csv
from nltk.corpus import stopwords
from thesaurus import Word
en_stops = set(stopwords.words('english'))
#print(en_stops)
l=['happy','happiness','pleasure','joy','glad'] #happy list
s=['sad','cry','tears','unhappy','pain','wounded','sadness','depressing','depression'] #sad list
fl=['fear','threatened'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 22:38:24 2020
@author: Eric Tzimas
"""
from tkinter import *
import math
from Solver import Solver
# Creating the Tkinter window
window = Tk()
window.configure(bg="white")
# Defining the size of the window in width and height using the 'geometry... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.