text stringlengths 37 1.41M |
|---|
import tkinter
from tkinter import ttk
def go(*args): # 处理事件,*args表示可变参数
print(comboxlist.get()) # 打印选中的值
win = tkinter.Tk() # 构造窗体
win.title('网关控制小程序') # 顶层窗口名称
win.geometry("500x300+200+20") # 设置窗口大小
win.resizable(width=True, height=True) # 设置窗口是否可变,宽不可变,高可变,默认为True
comvalue = tkinter.StringVar() # 窗... |
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
array=[ 4,2,0,1,-94,100]
sorted=False
while(sorted==False):
sorted=True
for j in range(1,len(array)):
if(array[j-1]>array[j]):
temp=array[j-1]
array[j-1]=... |
"""Dual quaternion operations."""
import numpy as np
from ._utils import check_dual_quaternion
from ._conversions import (screw_parameters_from_dual_quaternion,
dual_quaternion_from_screw_parameters)
from ..rotations import concatenate_quaternions
def dq_conj(dq):
"""Conjugate of dual q... |
"""Utility functions for rotations."""
import warnings
import math
import numpy as np
from ._constants import unitz, eps, two_pi
def norm_vector(v):
"""Normalize vector.
Parameters
----------
v : array-like, shape (n,)
nd vector
Returns
-------
u : array, shape (n,)
nd un... |
"""
========================
Plot Straight Line Paths
========================
We will compose a trajectory of multiple straight line paths in exponential
coordinates. This is a demonstration of batch conversion from exponential
coordinates to transformation matrices.
"""
import numpy as np
import matplotlib.pyplot as... |
# Datetime
# Para treinar o uso da biblioteca datetime, execute as funções do código a seguir, tentando prever os seus resultados:
import datetime
d = datetime.date(2001, 9, 11)
tday = datetime.date.today()
print(tday, d)
# datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, h... |
# Dicionario: Um dicionário é uma coleção, assim como as listas e as tuplas. Porém, enquanto as tuplas eram indexadas por um índice, os dicionários são indexados
# por chaves. Todo elemento em um dicionário possui uma chave e um valor. Chaves tipicamente são strings, valores podem ser qualquer tipo de dado.
# Crian... |
# Manipulação de Arquivos:
# # Abrir arquivo: 1°) cria uma variavel onde vai receber o retorno do método; 2°) método open() onde passa o parametro o caminho(path) do arquivo se tiver na
# # mesma pasta do projeto entao é so digitar o nome do arquivo; 3°) forma de abertura do arquivo, nesteb exemplo utilizaremos o... |
'''
To delete a file, you must import the OS module, and run its os.remove() function:
'''
import os
#Deleting a file
os.remove("demofile.txt")
#Checking wheather the file exists in directory or not
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist... |
from collections import Counter
inp = input()
hc_hash = {}
for i in inp:
if i not in hc_hash:
hc_hash[i] = 0
hc_hash[i] += 1
print(hc_hash)
values = Counter(hc_hash.values())
print(values)
if len(values) > 2:
print("NO")
elif len(values) == 2:
a, b = values.keys()
t = (values[a] == 1 or va... |
import json
# JSON file
f = open ('data.json', "r")
# Reading from file
data = json.loads(f.read())
# Iterating through the json
# list
for i in data['bmi_details']:
print(i)
# from user response for check the BMI condition
def bmicalculator():
Genter = input("Enter the genter : ")
Hei... |
# Task
# Given a string with a lot of indian phone numbers starting from +91
import re
str = "Hello mere dosto mere pas kuch no. " \
"hain +919425635125, +912534587965 aur batau kya +913265254789, +914587496584 aur +914257865 last wala nahi ana chahiye"
patt = re.compile(r'\b91\d{10}')
matches = patt.find... |
#Python Morsels
import re
def count_words(sentence):
list_of_words = re.split("[^\w']|\s+", sentence)
dict_words = {}
for word in list_of_words:
if word != "":
if not word in dict_words:
word = word.lower()
dict_words[word] = 1
else:
... |
#Python Morsels
import math
import re
def rounding(grade):
decimal_part = grade - int(grade)
if decimal_part >= 0.5:
grade = math.ceil(grade)
else:
grade = math.floor(grade)
return grade
def percent_to_grade(grade, **ksuffix):
if 'round' in ksuffix and ksuffix['round'] == True:
... |
import random
class InvalidChoice(Exception):
pass
class Choice(class):
""" Describes a question option (choice), its reference code (e.g. Q21a), and the value that
selecting this Choice represents to the test.
"""
def __init__(self, text, code, value):
self.text = text
self.valu... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 24 15:27:59 2020
@author: Li
"""
import math
row_string = ["innermost circle", "second innermost circle", "second outermost circle", "outermost circle"]
col_string = ["5.5 o'clock", "4.5 o'clock", "3.5 o'clock", "2.5 o'clock", "1.5 o'clock", "12.5 o'clock", "1... |
#day 5 Binary Representation
num=int(input("Enter the Number"))
def bin(i):
if i>1:
bin(i//2)
print(i%2,end=" ")
bin(num)
print()
|
import re
import sys
"""
Assumptions:
all IP addresses are only lowercase alpha characters
TO NOTE: These palindrome functions have been modified from the
originals in palindromes.py - TODO added about consolidating
"""
def check_for_palindromes(strings=[]):
palins = []
for word in strings:
... |
'''
n=input("who are you?")
print("hii",n,"how are you?")
age=int(input("how old are you?"))
print("so you are",age,"good")
'''
'''
# add two numbers type1 prefered
a=int(input(Enter no))
b=int(input(enter second no))
print(a,"+",b,"=",a+b)
'''
# type 2 conventional multiple ip
'''
print("Enter two nu... |
fruits = ['ca', 'at', 'ddd', 'cd', 'ab', 'appl', 'a']
##for i in range(0,15,3):
## print(i)
## print reverse list and reversed text
for i in range(len(fruits)):
index = len(fruits) - i
item = fruits[index - 1];
##print(item)
##print(len(item))
toPrint=''
for b in range(len(item)):
... |
"""
Escribe un programa que nos pida por teclado dos números enteros y que
a continuación muestre en pantalla la suma de los dos números solamente si
son los dos positivos. Si no se cumple que los dos números sean positivos
se visualizará un mensaje indicándolo.
La salida ha de tener el siguiente formato:
“La suma de l... |
"""
8.Escribe un programa que pida por teclado dos números y que muestre
en pantalla uno de los dos mensajes siguientes en función de los
números leídos:
a) el primer número (valor) es mayor que el segundo(valor)(introduciendo el valor de los números en el mensaje)
b) el primer número (valor) es menor que el segundo (v... |
"""
14.Escribe un programa que pida por teclado una cantidad de dinero y que a
continuación muestre la descomposición de dicho importe en el menor número
de billetes y monedas de 100, 50, 20, 10, 5, 2 y 1 euro.
En el caso de que alguna moneda no intervenga en la descomposición no se
tiene que visualizar nada en la pant... |
"""
10.Modifica el programa anterior para que en vez de mostrar un mensaje genérico
en el caso de que alguno o los dos números sean negativos, escriba una salida
diferenciada para cada una de las situaciones que se puedan producir,
utilizando los siguientes mensajes:
a) No se calcula la suma porque el primer número es ... |
import pandas as pd
def stat_function():
'''This function take input from user and give output with respect to the input number.
You can select number 1 to read minimum value, number 2 to get maximum value,
number 3 to get mean and mumber 4 for standard deviation.'''
print("Type 1 for minimum ... |
"""
Summary
---------
Code collection to take collection of csvs and upload to database
Detail
---------
For each exercise:
Load all levels from csvs
For each level, create a hash
See if already exists in database, upload as new entry if not
Create exercise as a list of levels
If exercise is different from everyt... |
#Case que separar las variables/constantes de las etiquetas
class VariableOConstante:
#En este diccionario se guardaran todas las variables o constantes
variables = {}
etiquetas = []
etiqfinal={}
i=0
def VarOEtiq(self,sentencia):
#Se mandara a un funcion interna que la procesara la etiqueta
self.Etiqueta(sen... |
class Name:
# constructor - instantionation = create an instance of a class
def __init__(self, first, middle, last):
self.first = first
self.middle = middle
self.last = last
# to-string methond
# this def is what is resturned when you call the class on its own
# i.e print(aNme)
def ... |
print('This program calculates factorials. What number\'s \
factorial would you like to calculate?')
num = int(input())
fact = 1
if num < 100:
for i in range(1, num + 1):
fact = fact * i
print(str(num) + '! is ' + str(fact) + '.')
else:
print('I\'m a wee computer and can\'t process that high just ye... |
# #fpr known sets of data
# # # grades = [71, 81, 77, 84]
# # # # for i in range(len(grades)):
# # # # grades[i] = grades[i] + 5
# # # print(grades)
# # # grades = [grade + 5 for grade in grades]
# # # print(grades)
# # words = ['NOW', 'HELLO', 'IS', 'HOW']
# # print(words)
# # words = [word.lower() for word in wor... |
def take(num, lyst):
tlist = []
for i in range(0, num, -1):
print(i)
tlist.append(lyst[i])
return tlist
def drop(num, lyst):
dlist = []
for i in range(num, len(lyst), -1):
print(i)
dlist.append(lyst[i])
return dlist
names = ['Ray', 'Martin','Lewis', 'LaBron', ... |
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
def rotate(lst, x):
x = -x
d = deque(lst)
d.rotate(x)
return d
if __name__ == '__main__':
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().rstrip().spl... |
#DiceGame
import random
import time
roll_again = "YES"
yes_list = ["YES","Y"]
while roll_again in yes_list:
print("\nRolling the dice...")
time.sleep(1)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print("The value are :")
print("Dice 1 =", dice1, "\nDice 2 =", dice... |
import torch.nn as nn
import torch.nn.functional as F
class ImageClassifier(nn.Module):
def __init__(self):
super(ImageClassifier, self).__init__()
# A convolution layer convolves the input tensors into a more abstract / higher-level representation which help
# to combat overfitting duri... |
'''
like a house
HAVC specialist: Type1
Electrician: Type2
new operations
various elements of an existing class hierarchy
'''
import abc
class House: #The class being visited
def accept(self, visitor):
# Trigger the visiting operation!
visitor.visit(self)
def work_on_hvac(self, hvac_specia... |
num=int(input("enter number"))
for i in range(1,num):
if num%i==0:
print(i)
~
|
a = 5
b = 10
if a > b:
print("Apple is red.")
else:
print("Apple is not red.")
|
clothes = ("t-shirt", "trousers","jeans","shirt")
for x in clothes:
if x == "jeans":
break
print(x)
|
num1 = 20
num2 = 5
quotient = num1 // num2
print("Quotient of a number =" , quotient)
|
""" A program that implements the logic for a Tic-Tac-Toe game
on an arbitrary size square board, e.g. 4x4, 5x5, etc.
author: fizgi
date: 23-Apr-2020
python: v3.8.2
"""
import random
from typing import List
from functions import initializer, print_board, row_checker, col_checker,\
dgn_lr_checker, d... |
# Instructions:
# …… Create a file called comprehensions.py.
# …… Create a list that prompts the user for the names of five people they know.
# Run the provided program. Note that nothing forces you to write the name “properly”—e.g., as “Jane” instead of “jAnE”. You will use list comprehensions to fix this.
# …… First... |
## Counter Controlled Loop ##
counter = 0
while counter < 5:
print counter
counter += 1
## Sentinel Controlled Loop ##
sentinel = ''
while sentinel != "0":
sentinel = input("Enter a number: ")
popup("You entered " + sentinel)
## For Loop ##
for myNum in range(5):
print "For " + str(myNum) |
list1 = []
kolom = input("Masukkan kolom untuk matriks : ")
baris = input("Masukkan baris untuk matriks : ")
i = 0
while (i<int(kolom)):
x = 0
while (x<int(baris)):
list1.append(input("A["+str(i)+"]["+str(x)+"] : "))
x = x + 1
i = i + 1
print ("\n")
print ("Hasil matriks tersebu... |
class doubly_linked_list:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
def __init__(self):
self.head = None
def append(self, data):
node = self.Node(data)
if(self.head):
t... |
from collections import deque
def solution(heights):
answer = []
for i in range(len(heights)-1,0,-1):
sent = False
for j in range(i-1,0,-1):
if heights[j] > heights[i]:
sent = True
answer.append(j+1)
break
if sent == False:
... |
from dice import Dice
from random import randrange
class Fuzion(Dice):
def __init__(self):
self.__c_failure = 3
self.__c_success = 18
self.__roll_statistics = []
self.__last_result = 0
self.__margin_of_succ_or_fail = 0
def Rand_method(self, num, sides):
re... |
class ngram_mention_extractor(object):
""" Returns all ngrams as a python list"""
def get_mentions(self, query, n = 0):
words = query.split(" ")
if n == 0:
n = len(words)
mentions = []
for length in reversed(range(1, n+1)):
for start_index in range(0,... |
num = int(input('մուտքագրել երկնիշ թիվ՝ '))
print(num//10+num%10)
# #extended version
# while True:
# num = input('Մուտքագրեք երկնիշ թիվ՝ ')
# if len(num)!=2:
# print("Թույլատրվող նիշերի քանակն է ԵՐԿՈՒ:\n")
# else:
# try:
# num = int(num)
# except:
# print("Թույլատրվում են միայն ԹՎԵՐ:\... |
num = int(input("enter a nonnegative number: "))
num_str = str(num)
num_str = num_str[-2:]
num_str = int(num_str)
last_two_index = num_str//50*50
num_index = num//50*50
print(num_index+last_two_index) |
def mult(samp_list):
total = 1
for number in samp_list:
total *= number
return total
samp_l = [6, 2, -3, 1, 5]
print(mult(samp_l)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 13:19:42 2019
@author: hoeinnkim
"""
import pandas as pd
df = pd.DataFrame([[15,'남','덕중'],[17,'여','수리']],
index=['호우','헤이'],
columns=['나이','성별','과목'])
print(df)
df.index = ['학생1','학생2']
df.columns = ['연령','... |
"""
calc.py
Parser and evaluator for mathematical expressions.
Uses pyparsing to parse. Main function is evaluator().
Heavily modified from the edX calc.py
"""
from __future__ import division
import numbers
import operator
import numpy as np
from pyparsing import (
CaselessLiteral,
Combine,
Forward,
... |
#!/usr/bin/env python
# coding: utf-8
# # list
# In[1]:
# list[element1, element2, element3]
# 0 1 2
l1 = [123, 'Bee', 'A.I']
# -3 -2 -1
l1
# In[2]:
#dic[item1, item2, item3]
#item = key:value
d1 = {'id': 2,
'name' : 'Bee',
'course' : 'A.I',
'admission' : '2019-12-15',
... |
"""Create a Python web crawler"""
#Crawl entire site and gather links
import os
#Each website that is crawled is a separate project (folder)
def createProjectDirectory(directory):
if not os.path.exists(directory):
print 'Creating Project' + directory
os.makedirs(directory)
#Create queue and crawl... |
#Calculate power by iterative method
def iterPower (base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
ans = 1
for i in range(exp):
ans *= base
return ans
|
#Importing all math functions from Python's math library
from math import *
# Defining polysum fucntion which calculates the sum of
# area and square of the perimeter of the regular polygon
def polysum (n,s):
'''
n: number of sides of a Polygon
s: length of each side of a Polygon
n and s can be int or ... |
#following Udemy course: 100 days of code by Angela Yu
import random
print('\n\n----------------Flip a coin------------')
input("If you are ready, type: go\n")
random_int = random.randint(0,1)
if random_int == 0:
print('Heads')
elif random_int == 1:
print('Tails')
else:
print('CHeck your code!')
... |
"""
implementation of paper by Sertac Karaman in 2010
http://roboticsproceedings.org/rss06/p34.pdf
"""
import sys, random, math, pygame
from pygame.locals import *
from math import sqrt,cos,sin,atan2
import time
#constants
XDIM = 640
YDIM = 480
WINSIZE = [XDIM, YDIM]
EPSILON = 10.0
NUMNODES = 5000 #samples/iterations
R... |
#改编了一下这里的20题如下:登陆中国联通网上营业厅 后选择「自助服务」-->「查询」-->「账户余额」,然后输出手机号码和可用额度。
# 参考 http://www.cnblogs.com/LanTianYou/p/6432953.html
from selenium import webdriver
import selenium.webdriver.support.ui as ui
def login_query_10010(username,pwd):
print(username,pwd)
driver=webdriver.PhantomJS()#需要安装PhantomJS,安装方法参考http://w... |
name = "Gentleman"
print("Hello " + name + " How are you?") #string concatenation
que = "How about you?"
print("Hello " + name + " " + que)
|
n = int(input("Enter n:"))
i = 1
while (i<=n//2+1):
if (i%2==1):
print(i)
i=i+1 |
n = int(input("Enter value of n: "))
i = 1
while (i<=n*2):
if (i%2==0):
print (i)
i=i+1 |
a = 21
b = 7
print(str(a) + " + " + str(b) + " = " + str(a+b)) #addition
print(f"{a} - {b} = {a-b}") #Substraction
print("{} * {} = {}".format(a, b, a*b)) #multiplication
print("{x} / {y} = {div}".format(y=b, x=a, div=a/b)) #Division
print(f"{a} // {b} = {a//b}") #floor divison
print(f"{a} % {b} = {a%b}") #remainder/m... |
n= int(input("Enter n:"))
for i in range (1,n*2+1,2):
print(i) |
n=int(input("enter a number:"))
if n%400==0:
print("it is a leap year")
elif n%100==0:
print("it is not leap year")
elif n%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
|
class Node:
def __init__(self,data):
self.data=data
self.nxt=None
class LinkedList:
def __init__(self):
self.head=None
def insertatbeg(self,data):
newnode=Node(data)
newnode.nxt=self.head
self.head=newnode
def delete(self):
tmp=self.head
... |
str1=str(input("enter a string:"))
a=str1[0:2]
b='Is'
if a==b:
print(str1)
else:
print('Is'+str1)
|
# Created on: 070421
# Author: jasshanK
# Description: Testing pan mechanism of turret
from time import sleep
import pigpio
EN = 6
DIR = 22 # direction GPIO pin
STEP = 27 # step GPIO pin
step = 50
delay = 3000 * (10 ** -6)
CW = 1 # clockwise
CCW = 0 # counter clockwise
yaw = 0 # keep track of relative position ... |
print("MENU\n1. Insert a number and ** by 3\n2. Insert 4 IPs to a list and print it\n3. Insert 4 entries to DNS_Dictionary and print it\n4. check if a string is polindrom")
menu_num = int(input("Choose a number between 1 - 4\n"))
if (menu_num == 1):
num = int(input("Choose your number: "))
print ("The n... |
#!/usr/bin/env python3
"""
Based off of: http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
To run this script, type:
python3 buyLotsOfFruit.py
Once you have correctly implemented the buyLotsOfFruit function,
the script should produce the output:
Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12... |
import os
os.chdir('/Users/Hatim/Desktop/Git Repos/AdventOfCode/Day 5/')
text_file = open('input.txt', 'r')
string = text_file.read().rstrip()
def explosion(string, i):
return string[:i] + string[i+2:]
def reaction(string):
length = len(string)
index = 0
while index < (length - 1):
if index <... |
def prime_number(num):
if (num == 1):
print (1)
elif (num == 0):
print ("input a number larger than 0")
else:
primes = [1]
for i in range(2, num):
for d in range(2, i):
if((i%d) == 0):
break
else:
if(d == (i-1)):
primes.append(i)
print(primes)
prime_number(20)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# 0 node in list
if head is None:
return None
# 1 node... |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
is_minus = False
if x < 0:
is_minus = True
answer = ""
x = str(x)
for i in range(len(x)):
if x[len(x) - i - 1] != "-":
answer... |
def addNumber(X,Y):
print(X+Y)
def minusNumber(X,Y):
print(X-Y)
def multiply(X,Y):
print(X*Y)
def divide(X,Y):
print(X/Y)
addNumber(10,20)
minusNumber(20,10)
multiply(20,10)
divide(20,10)
|
def swapFileData():
filename = input("enter the file name: ")
with open(sample1,'r') as a:
data_a = a.read()
with open(sample2,'r') as a:
data_b = b.read
with open(sample1,'w') as a:
a.write(data_b)
with open(sample2,'w') as a:
b.write(data_a)
swapFi... |
from pymongo import MongoClient
import datetime
ts = datetime.datetime.now().timestamp()
#converting timestamp to proper format
import time
readable = time.ctime(ts)
def insert_data(collection,collection_data): #insert the data in collection
rec_id1 = collection.insert_one(collection_data)
print("Data inserte... |
#!/usr/bin/env python
#------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.... |
def drink(x):
count = x # 喝了多少瓶酒
k1 = x # 多少空瓶子
k2 = x # 多少瓶盖
while k1 >= 3 or k2 >= 7:
while k1 >= 3:
change = k1 // 3
count += change
k1 %= 3
k1 += change
k2 += change
while k2 >= 7:
change = k2 // 7
... |
#
'''
Class gameProblem, implements simpleai.search.SearchProblem
'''
import simpleai.search
from simpleai.search import SearchProblem, astar
# --------------- GameProblem Definition -----------------
class GameProblem(SearchProblem):
# Object attributes, can be accessed in the methods below
MAP=No... |
class MapCharacter:
def __init__(self,str1,str2):
self.str1 = str1
self.str2 = str2
self.can_map =True
def checkcharactermap(self):
if len(self.str1) is not len(self.str2):
return False
else:
charmap = {}
i=0
for i in ran... |
#Look for #IMPLEMENT tags in this file. These tags indicate what has
#to be implemented.
import random
import sys
'''
This file will contain different variable ordering heuristics to be used within
bt_search.
var_ordering == a function with the following template
ord_type(csp)
==> returns Variable
... |
##!/usr/bin/python
# Filename: p1.py
import sys
##### ADD YOUR NAME, Student ID, and Section number #######
# NAME:
# STUDENT ID:
# SECTION:
###########################################################
########### ADD YOUR CODE HERE ###############################
def is_float(s):
try:
float(s)
r... |
def findWord(str1, str2):
for c in str1:
if str2.find(c) < 0:
return "No"
return "Yes"
str1 = input("String 1: ")
str2 = input("String 2: ")
print(findWord(str1,str2)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sqlite3
conn = sqlite3.connect('proyect.db')
c = conn.cursor()
cant_solitar = 0
def ejecutarQuery(consulta):
c.execute(consulta)
existen = c.fetchall()
#Regresa falso si no hay ordenes que pedir, si no, regresa el arreglo de listas... |
import ticker as yf
from typing import Optional, Tuple, List
def get_price_change(
ticker: str,
lookback: Optional[str] = "2d"
) -> Tuple[float, List]:
"""Gets price change for a particular ticker
Args:
ticker (str): Ticker of interest. E.g., BABA or Y92.SI
lookback (str, opti... |
# Valid Triangle Array
class Solution:
"""
@param nums: the given array
@return: the number of triplets chosen from the array that can make triangles
"""
def triangleNumber(self, nums):
# Write your code here
nums = sorted(nums)
total = 0
for i in range(len(nums)-2):... |
class MinStack:
def __init__(self):
# do intialization if necessary
self.stack = []
self.minStack = []
"""
@param: number: An integer
@return: nothing
"""
def push(self, number):
# write your code here
self.stack.append(number)
if len(self.mi... |
"""Definition of a mock keyboard for use in testing."""
from typing import Optional
from shimmer.keyboard import KeyboardHandler
class MockKeyboard:
"""
A mock of a physical keyboard.
Used to simulate keyboard events in tests.
"""
def press(
self, handler: KeyboardHandler, symbol: int,... |
"""A mock mouse for use in testing."""
from typing import Optional, Tuple
from pyglet.window.mouse import LEFT
from shimmer.components.box import Box
class MockMouse:
"""
A mock of a physical mouse.
Used to simulate mouse events in tests.
"""
def box_center_in_world_coord(self, box: Box) -> T... |
class node:
def __init__(self, value = None, left = None, right = None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
class b_s_tree:
c = node()
def __init__(self):
self.root = None
def __str__(self):
... |
def printer(arg):
print "Hello Anand! %r" %arg
printer("sudhan")
print "Working with files and functions"
from sys import argv
script, fname=argv
def printfile(f):
print f.read()
def rewindfile(f):
f.seek(0)
def printline(line,f):
print line,f.readline()
file1=open(fname)
print "PRINT... |
mystring=" I wAlK tO sChOoL"
print(mystring.count('o'))
print(mystring.find('o'))
print(mystring.lower())
print(mystring.upper())
print(mystring.replace('o','sno'))
print(mystring.strip()) |
firstList=[1,2,3,4,5,6,1,2,3,4,5,6]
print(firstList)
print(firstList.count(3)) #counts the number of occurrences of '3' in the list
print("this is the out put for the count function")
print(firstList.index(3)) #returns the index of '3' in the list
print("this is the out put for the index function")
print(firstLis... |
import math
n=int(input())
motu=[]
patlu=[]
for i in range(1,math.floor(n/3)):
patlu.append(i)
motu.append(2*i)
s=int(sum(patlu)+sum(motu))
if s>n:
break
a=patlu[len(patlu)-1]
motu.remove(motu[len(motu)-1])
sum=int(int(sum(patlu))+int(sum(motu)))
motu.append(n-sum)
b=motu[len(motu)... |
#linear algebraic operations
import numpy as np
a=input("Enter the 2nd matrix:")
b=input("Enter the 2nd matrix:")
x=np.array(a)
y=np.array(b)
print("matrix algebraic operations")
a=[x,y,np.add(x,y),np.subtract(x,y),np.dot(x,y),np.divide(x,y),np.transpose(x),np.transpose(y),np.linalg.det(x),np.linalg.det(y),np.linalg.in... |
"""
类的静态方法, 私有方法和私有字段
"""
class WhoAreYou(object):
def __init__(self, name, age):
self.name = name
self.__age = age # 私有字段
# 私有方法
def __delete(self):
print('delete %s' % self.name)
def shachu(self):
self.__delete()
def show(self):
print(self.__age)
... |
'''
三级菜单选择, 任何时候输入q 可退出, 输入b 可跳到一级菜单,
question: 输入不存在的值时,没有处理
'''
data = {
'a': {'a1': ['a11','a12','a13'], 'a2': ['a21','a22','a32'], 'a3': ['a31','a32','a33']},
'b': {'b1': ['b11','b12','b13'], 'b2': ['b21','b22','b32'], 'b3': ['b31','b32','b33']},
'c': {'c1': ['c11','c12','c13'], 'c2': ['c21','c22','c32'... |
data = {
'aaa': 123,
'bbb': 123
}
count = 0
while count < 3:
username = input('Please input your username:')
password = input('Input your password:')
if username in data.keys():
if int(password) == data[username]:
exit('Login OK!')
else:
print('Information Error')
... |
"""
装饰器框架: 带参数的装饰器
"""
def before(request, kargs):
print('before')
def after(request, kargs):
print('after')
def filter(before_func, after_func):
def outer(main_func):
def wrapper(request, kargs):
before_result = before_func(request, kargs)
if before_result != None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.