text stringlengths 37 1.41M |
|---|
import numpy as np
A = np.arange(3,15).reshape(3,4)
print(A)
print(A[2])
print(A[2][1])
print(A[:,1])
print(A[1,1:2])
print(A.T)
for row in A:
print(row)
for column in A.T:
print(column)
print(A.flatten())
for item in A.flat:
print(item)
A = np.array([1,1,1])
B = np.array([2,2,2])
C = np.vstack((A,B))... |
from collections import OrderedDict
class Dog():
""" Description of the class"""
def __init__(self, name, age):
self.name = name #any variable with the predix self is available to every method in the class
self.age = age
self.gender = "male"
def sit(self):
"""simulate a puppy sitting"""
print(self.name.... |
print ("How old are you?"),
age = int(input())
print ("How tall are you?"),
height = input()
print ("How much do you weight?"),
weight = input()
print ("so you are {} old, {} tall, and {} heavy".format(age, height, weight))
exit() |
from NodoMatriz2 import matriz2
class listaenlazada2:
def __init__ (self):
self.cabeza=None
def insertar(self,m,n,nombre,p,Filas2):
nuevo=matriz2(m,n,nombre,p,Filas2)
if self.cabeza is None:
self.cabeza=nuevo
else:
tmp=self.cabeza
while tmp.siguiente is not... |
import random
def rng(a,b):
ran = random.randint(a,b)
return ran
def montyalways():
if selection == prize:
return False
else:
return True
def montynever():
if selection == prize:
return True
else:
return False
games = input("Number of games to... |
#import statistics module to use function to solve for standard deviation
import statistics
#define functions for all equations in program: standard deviation, average, max difference, and min difference
def stddev(s):
return statistics.stdev(s)
def average(s):
return sum(s) / len(s)
def maxdif(a,b... |
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
names=dict()
for line in handle:
if not line.startswith("From:"): continue
line = line.rstrip()
word= line.split()
addy=word[1]
names[addy] = names.get(addy,0)+1
largest=-1
theword=None
... |
import tkinter as tk
import tk_tools
import random
import string
def random_letters():
sal = string.ascii_letters
return (random.choice(sal)
+ random.choice(sal)
+ random.choice(sal))
def add_row_random():
r1 = random_letters()
r2 = random_letters()
r3 = random_letters()
... |
import tkinter as tk
class ToolTip(object):
"""
Add a tooltip to any widget.::
entry = tk.Entry(root)
entry.grid()
# createst a tooltip
tk_tools.ToolTip(entry, 'enter a value between 1 and 10')
:param widget: the widget on which to hover
:param text: the text to disp... |
from . import Solver
from . import Digits_extractor
import sys
def main():
try:
file = sys.argv[1]
except Exception:
raise Exception("A file name is needed !")
if file == "--help":
print("""Usage: Solve.py filename outputname(optionnal)
filename is required
outp... |
print "que numero es mayor que el otro"
print "introduce el primer numero"
primero = int(raw_input())
print "introduce el segundo numero"
segundo = int(raw_input())
if primero>segundo:
primero ,"es mayor que", segundo
else:
segundo ,"es mayor que", primero
|
import numpy as np
import cv2 as cv
import sys
# Returns the coordinates of the points where the meniscus intersects with the tongue.
# The user selects the points from the inputted video (array of images)
# The inputted video must be a numpy array and can be black and white or color
def get_meniscus(selected_frames,... |
def countPos(l):
pos = 0
for e in l:
if e>0:
pos+=1
return pos
'''
Returns the number of elements of the list l that are positive.
>>> countPos([1, -4, 0, 4, 8, 0])
3
'''
def dotProduct(v1, v2):
summand = 0
while v1 != [] and v2!= []:
summand += v1[... |
fib = open("2600-0.txt")
line = fib.read()
def rotate_pair():
for i in line:
word = line.strip()
b = word.sort()
c = 0
if b[i] == b[i+1]:
print(b)
c = c + 1
my_set = set(b)
print("Unique words are:", my_set)
|
#!/usr/local/bin/python
#
import RPi.GPIO as GPIO
import time
from time import sleep
GPIO.setmode(GPIO.BCM)
# Defines the number of times that the LED should flash when the calorie intake exceeds 100% of the daily recommended dosage.
cycles_for_cal100 = 3
# This function sets up the LED which serves to nudge the us... |
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
arr1=nums[0:len(nums)//2]
arr2=nums[len(nums)//2:len(nums)]
print(arr1)
print(arr2)
result=[]
for i in range(len(arr1)):
result.append(arr1[i])
result.append(arr2[i])
... |
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
def helper(number):
string = str(number)
for i in string:
if int(i) == 0:
return -1
if number % int(i) != 0:
... |
class Solution:
def reverse(self, x: int) -> int:
def reverse(num):
if num < 0:
num = str(num)[1::]
num = int(str(num)[::-1])
return -num
else:
num = int(str(num)[::-1])
return num
if (-2) ** 31 <= x ... |
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
# model = Sequential([
# Dense(32, input_dim=784),
# Activation('relu'),
# Dense(10),
# Activation('softmax'),
# ])
# For a single-input model with 10 classes (categorical classification):
model = Sequential... |
# My Name
# Prints my name to the screen
print ("Trent")
input("\n\nPress enter to continue")
|
import unittest
from models.location import Location
class TestLocation(unittest.TestCase):
def setUp(self):
self.spin_room = Location("spin room", 10)
self.tiny_room = Location("wee room", 3)
def test_room_id_is_none(self):
self.assertTrue(self.spin_room.id == None)
def test_room... |
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
import seaborn as sea
iris_data = pd.read_csv('../iris.csv', index_col="Id")
print(iris_data.head())
# Histogram
# sea.distplot(a=iris_data['Petal Length (cm)'], kde=False)
"""
a= chooses the column we'd like to plot
kde=... |
import pandas as pd
"""
- dtype shorthand for data type
- dtype(object) returns the data type
- can use dtype to grab the specific type of column
"""
reviews = pd.read_csv('../winemag-data-130k-v2.csv', index_col=0)
print(reviews.price.dtype)
print("------------")
print()
# can also get the data types for every co... |
# -*- coding: utf-8 -*-
a=input();
b = a.split(" ")
m = int(b[0])
n = int (b[1])
if(m>n):
print(m)
elif(n>m):
print(n)
elif(n==m):
print(n) |
import heapq
class PriorityQueue(object):
def __init__(self):
self.qlist = []
def __len__(self):
return len(self.qlist)
def isEmpty(self):
return len(self) == 0
def enqueue(self,data,priority):
heapq.heappush(self.qlist, (priority,data))
self.qlist.sort(... |
#!/usr/bin/env/ python
# ECBM E4040 Fall 2018 Assignment 2
# This Python script contains various functions for layer construction.
import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a ... |
from tkinter import *
root = Tk()
root.title("Simple calculator")
root.iconbitmap('C:/Users/simao/OneDrive/Ambiente de Trabalho/Projects/Python/dinal_deal.ico')
e = Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def button_click(number):
current=e.get()
... |
#!usr/bin/python
#defines vector object
import math
class vector:
v = []
#constructor
def __init__(self, a):
self.v = a
#instance methods
def magnitude(self):
sum = 0
for i in range(len(self.v)):
sum += self.v[i]^2
return math.sqrt(sum)
def multiply(self, factor):
for i in self.v:
i *= ... |
#------------------------------------
# Name: Dylan Markovic
# Class: CS372
# Assignment: Project 1
# Due Date: 2.11.2018
#------------------------------------
import sys
from socket import *
MESSAGE_LENGTH = 500
HANDLE_LENGTH = 10
#--------------------------
# checkArgs makes sure the client inputs the co... |
def recurse(n):
# check for base case
if (n <= 0):
return 0
else:
# recursive case
# print(n)
return 1 + recurse(n-1)
recurse(10)
# Computes the sum of numbers from 0 to n
def sum(n):
if (n <= 0):
return 0
else:
# print(n)
return n + sum(n-1)
... |
import numpy as np
from sklearn.model_selection import ShuffleSplit
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
y = np.array([1, 2, 3, 4, 5, 6])
rs = ShuffleSplit(n_splits=3, test_size=0.25, random_state=0)
rs.get_n_splits(X)
print(rs)
for train_index, test_index in rs.split(X, y):
print("Tra... |
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
row = [set() for i in range(0, 9)]
col = [set() for i in range(0, 9)]
grid = [set() for i in range(0,... |
class Solution(object):
def countCharacters(self, words, chars):
"""
:type words: List[str]
:type chars: str
:rtype: int
"""
result = 0
charsArr = [0 for i in range(26)]
for char in chars:
charsArr[ord(char) - ord('a')] += 1
for wor... |
# 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 hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: i... |
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
row = len(board) - 1
if row <= 0:
return
col = len(board[0]) - 1
quene = []
for... |
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
s... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
result = ListNode(0)... |
class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
result = 0
lengthA = len(A)
start = 0
end = lengthA
# filter down
while start + 1 < lengthA:
if A[start] >= A[start + 1]:
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: L... |
# prints the prime factorization of the user's number
#gets number from user
print ("Insert a number:")
num = int(input())
ori = num
#breaks down the number into its prime factorization in order
a = []
while(num > 1):
for count in range(2, num+1):
print(num, count)
if(num % count == 0):... |
print("the number of a's in banana are :::"+str('banana'.count('a')))
|
def do_n(func,n):
if(n==0):
return 1
else:
return n+do_n(func,n-1)
n=int(input("Enter the value"))
print("The Sum of values from 0 to %d is %d"%(n,do_n(do_n,n)))
|
val=input("Please enter a string::")
if(len(val)<3):
pass
elif val[len(val)-3:] =='ing':
val=val+'ly'
else:
val=val+'ing'
print("The string is :::"+val)
|
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
print('The middle with 2 char::'+middle("AK"))
print('The middle with 1 char::'+middle("A"))
print('The middle with 0 char::'+middle(""))
print('The first with 2 char::'+first("AK"))
print('The first with... |
def histogram(word):
dic={}
for char in word:
if char in dic:
dic[char]+=1
else:
dic[char]=1
return dic
def is_anagram(s1,s2):
if len(s1)!=len(s2):
return False
else:
dic_s1=histogram(s1)
dic_s2=histogram(s2)
for key in dic_s1:... |
'''
As long as you have a URL, the webbrowser module lets users cut out the step of
opening the browser and directing themselves to a website. Other programs could
use this functionality to do the following:
AIM: Open all links on a page in separate browser tabs.
'''
### LIBRARIES WE'RE GOING TO NEED ###
# WEBBROWSER... |
Sample_list=[8,2,3,-1,7]
def multi(Sample_list):
result=1
for i in Sample_list:
result=i*result
return result
a=multi(Sample_list)
print (a)
|
# Implement a class to hold item information
class Item: #base class
"""
This is a item class with attributes
name & description
"""
def __init__(self, name, description):
self.name = name
self.description = description
def __repr__(self):
return f"{self.name}, {se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
class Student(object):
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score
def Student2dict(std):
return{
'name':std.name,
'age':std.age,
'score':std.sco... |
print "Simple Fizz-Buzz Game."
print "Type 'quit' to exit."
while True:
userInput = raw_input("Please enter a number: ")
try:
intVal = int(userInput)
print "Fizz-Buzz" if intVal%3 == 0 and intVal%5 == 0 else "Fizz" if intVal%3 == 0 else "Buzz" if intVal%5 == 0 else intVal
except ValueError:
... |
def main():
#Escribe tu código debajo de esta línea
import math
edad= int(input("Ingresa tu edad: "))
if edad>=18:
identificacion= str(input("¿Tienes identificación oficial? (s/n): "))
if (identificacion== "s"):
print ("Trámite de licencia concedido")
elif (identificacion== "n"):
prin... |
import random
cards = {'Hearts':
{'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11},
'Diamonds':
{'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Que... |
import requests
import hashlib
import sys
def request_data(query):
"""
Given the first 5 characters of a sha1 hash (query), request_data returns the request response after
trying to access the Pwnedpasswords API.
Keyword arguments:
query: a 5 charachter string corresponding to the first 5 characte... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 23:30:46 2019
@author: danilo
"""
def main():
x=eval(input("Give me x: "))
while(x!=1):
print ("{0:.0f}".format(x))
if(x%2==0):
x=x/2
else:
x=x*3+1
print ("{0:.0f}".format(x))
main() |
import mysql.connector
import connect
db = connect.koneksi()
#Menambahkan data baru ke dalam tabel pendaftaran
def add(data):
cursor = db.cursor()
sql = """INSERT INTO pendaftaran_pemeriksaan(tanggal,nomor_urut,nama,jenis_kelamin,umur,alamat) VALUES (%s,%s,%s,%s,%s,%s)"""
cursor.execute(sql,data)
db.co... |
# 2.
# DIM = 4 # dimension of the board DIMxDIM
# EMPTYSLOT = 0
# QUIT = 0
# def initialize_board():
# ''' Creates the initial board according to the user input.
# The board is a list of lists.
# The list contains DIM elements (rows), each of which contains DIM elements (columns)'''
# numbers = input()... |
import string
def open_file():
"""A function that takes the name of a file as an input and opens it"""
name = input("Enter name of file: ")
try:
my_file = open(name,"r")
return my_file
except FileNotFoundError:
print(("File {} not found!").format(name))
def scramble_middle(text... |
def read_file():
"""Askes the user for a file name and tries to open it"""
file_name = input("Enter filename: ")
try:
the_file = open(file_name,"r")
return the_file
except FileNotFoundError:
print("Filename {} not found!".format(file_name))
def file_to_list(file_to_read): #comm... |
def get_input():
"""gets the input from the user"""
user_input = input("Enter an ISBN: ")
return user_input
def input_to_list(the_input):
word_as_list = [item for item in the_input]
return word_as_list
def is_valid(input_as_list,LENGTH_OF_ISBN,PLACEHOLDER_POSITION):
if len(input_as_lis... |
def open_file(filename):
''' Returns a file stream if filename found, otherwise None '''
try:
file_stream = open(filename, "r")
return file_stream
except FileNotFoundError:
return None
def get_winning_numbers(NUMBERS_IN_LOTTO_ROW, HIGHEST_VALID_NUMBER):
"""askes for the winning... |
#!/usr/bin/env python
# coding: utf-8
import copy
def minor(A, i, j):
M = copy.deepcopy(A)
del M[i]
for i in range(len(A[0]) - 1):
del M[i][j]
return M
def det(A):
m = len(A)
n = len(A[0])
if m != n:
return None
if n == 1:
return A[0][0]
signum = 1
det... |
from dna import *
import random
class Population(object):
def __init__(self, target, mutation_rate, max_pop):
self.target = target
self.mutation_rate = mutation_rate
self.max_pop = max_pop
self.population = []
self.buildPopulation()
def buildPopulation(self):
fo... |
""""Estructura de una aplicación MVC
Definición de Modelos
Modelo: Incluye todos los datos y su lógica relacionada.
Definicion de Vistas
Vista: presentar datos al usuario o manejar la interacción del usuario (entrega las entradas del usuario)
Definición de controladores
Controlador: una interfaz entre los componentes... |
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# Author: kr.r
"""
文件的序列化与反序列化
"""
import json
import requests
r = requests.get(url='http://www.weather.com.cn/data/sk/101190408.html')
print(r.content.decode('utf-8'))
print(type(r.content.decode('utf-8')))
# 对文件进行序列化--》就是把服务端数据写到文件中
# json.dump(r.content.decode('ut... |
tinta = float(input("Digite a área do local que desejar pintar(m^): "))
litros = tinta / 6
latas = litros / 18
galoes = litros / 3.6
preco_latas = latas * 80
preco_galoes = galoes * 25
print('Quantidade de latas eh: '+str(latas))
print('O preco total eh de: '+str(preco_latas))
print('O preco total eh de: '+str(pre... |
country_a = 80000
country_b = 200000
while country_b > country_a:
print()
print('cA -> ' + str(country_a))
print('cB -> ' + str(country_b))
country_a = country_a + (country_a * 3/100)
country_b = country_b + (country_b * 1.5/100)
print()
print('cA -> ' + str(country_a))
print('cB -> ' + str(co... |
n = int(input('Digite o numero: '))
str_number = str(n)
str_len = len(str_number)
str_len = str_len - 1
while str_len >= 0:
print(str_number[str_len], end='')
str_len = str_len - 1
print()
|
print("Digite dois 2 numeros inteiros: ")
n1 = int(input())
n2 = int(input())
print("Digite o numero real: ")
n3 = float(input())
result_a = (n1*2*2)+(n2/2)
result_b = (3*n1 + n3)
print("Questao a: "+str(result_a))
print("Questao b: "+str(result_b))
|
name = input('Digite o seu nome, caro padawan: ')
aux = ''
counter = len(name)
lista = []
while counter >= 0:
print(name[:counter], end='')
print()
counter = counter - 1
|
import sqlite3
conn = sqlite3.connect("dati.db")
cursor = conn.cursor()
fine_inserimento = False
while not fine_inserimento:
cid = input("id: ")
nome = input("nome: ")
peso = input("peso: ")
sql = f"insert into coffee "\
f"(id, nome, peso) values "\
f"({cid},'{nome}',{peso})"... |
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def isLeaf(self):
if self.left == None and self.right == None:
return True
else:
... |
#cerco un numero indicato dall'utente
src = input("che numero vuoi? ")
for n in range(0,100):
print "n = ", n
if n == src:
print "trovato"
break
print "fine loop"
|
# -*- coding: utf-8 -*-
import pandas as pd
# 读取txt文件
def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = [_.strip() for _ in f.readlines()]
labels, texts = [], []
for line in content:
parts = line.split()
label, text = parts[0], ''.join(parts... |
"""
Class for Room
"""
class Room:
def __init__(self, room_id):
"""
Constructor for a room
Args:
room_id (string): the room's ID which is also its invite code
"""
self.room_id = room_id
self.controlled = []
self.controller = []
self.users ... |
# -*- coding:utf-8 -*-
"""
Author :Yxxxb & Xubing Ye
Number :1953348
Date :2021/10/09
File :象限法实现.py
"""
import matplotlib.pyplot as plt
def drawline(x, y):
for i in range(len(x)):
plt.plot(x[i], y[i], color='r')
plt.scatter(x[i], y[i], color='b')
def tellLocation(x, y):
assert (x != 0 ... |
from block import Block
# This file defines the class for a Blockchain.
class Blockchain:
# Initiate a list that will contain all the blocks, initiate a list for any unconfirmed transactions,
# and create and add the genesis block to to list.
def __init__(self):
self.chain = []
... |
def say_hi(name,age):
print("Hello "+name+", you are "+age +" years old.")
name = input("Enter your name: ")
age = input("Enter your age: ")
say_hi(name,age)
#say_hi("Professor",10) --> because in say_hi fucntion age is taken as string but for int it is not typecasted to string
say_hi("Professor","10")
|
name = "Janit Lodha"
print(name)
print("Janit\Lodha")
print("Janit\nLodha")
#Concatenation
print(name + " is a student of IIITA")
#Functions
print(name.lower())
print(name.upper())
print((name.upper()).isupper())
print(len(name))
print(name.index('ni'))
print(name.replace("Janit","Ashok"))
#Accessing elements using... |
#Append Mode
company_designations = open("Employees.txt","a")
#Checking the writability
print(company_designations.writable())
#Appending text in document
company_designations.write("\nPrateek - Human Resources")
company_designations.close()
#Overriding By Write Mode
company_designations = open("Employees.txt","w")... |
import sqlite3
import sys
conn = sqlite3.connect('./mydb.db')
cursor = conn.cursor()
#cursor.execute("DROP TABLE matrix")
#create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS matrix
(/*id int AUTO_INCREMENT NOT NULL PRIMARY KEY UNIQUE, */
row_num int,
col_num int,
value int)
""")
#insert multiple records... |
def IsDigit(a):
x = int(a) #input("Enter your number")
if (x / 1 == x):
return ("Yes")
def IsPossitive(a):
x = a
if (int(x) >= 0):
return ("Yes")
def checkBin(a):
p = set(a)
s = {'0', '1'}
if s == p or p == {'0'} or p == {'1'}:
return ("Yes")
else:
r... |
# coding:utf-8
"""
经典排序算法 - 地精排序Gnome Sort
号称最简单的排序算法,只有一层循环,默认情况下前进冒泡,
一旦遇到冒泡的情况发生就往回冒,直到把这个数字放好为止
java代码:
static void gnome_sort(int[] unsorted)
{
int i = 0;
while (i < unsorted.Length)
{
if (i == 0 || unsorted[i - 1] <= unsorted[i])
{
... |
# Edgar Castillo / Github: https://github.com/hellocastillo
# Copyright (c) 2021 Edgar Castillo
# The Blueprint for recursion
"""
def recursionMethod(parameters):
if exit from condition satisfied:
return some Value
else:
recursionMethod(modified parameters)
"""
# How the Recursion works
def fi... |
# Komment
class Base(object):
"""A Base is the underlying construct of the other classes defined here"""
# A Base can be created
def __init__(self):
# A Base has a Name
self.name = None
# A Base contains something
self.contains = None
# What else is Common ... |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
begin = 0
end = len(nums) - 1
while begin <= end:
mid = int((begin + end) / 2)
if nums[mid] == target:
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
... |
import random
from options import options
from utils import dictobj
class Gene(object):
"""
A gene represents a single allele.
Once created, it's value never changes
"""
def __init__(self, value=None):
if self.__class__ == Gene:
if random.random() < options.multi_chance:
... |
"""
Queues Python Introduction
As previously mentioned, a queue is a data structure that contains an ordered set of data that follows a
FIFO (first in, first out) protocol. You can visualize it as a line at a deli:
The customer at the front of the line (equivalent to the head in a queue) is the first customer to... |
"""
Queues Python Size
Bounded queues require limits on the number of nodes that can be contained, while other queues don’t. To account for
this, we will need to make some modifications to our Queue class so we can keep track of and limit size where needed.
We’ll be adding two new properties to help us out here:
... |
#Write a python function stats() that takes name of text file as an argument. The function
#should print the number of lines, words, and characters in the file. For example,
#>>>stats('example.txt')
#Line count: 3
#Word count: 20
#Character count: 98
def stat(txt):
num_lines = 0
num_words = 0
num_chars = 0
... |
#(b) Write a python program to implement a class called Adder that exports a method
#add(self, x, y) that prints a “Not Implemented” message. Then define two subclasses of Adder that implement the add method:
#1. ListAdder, with an add method that returns the concatenation of its two list argu¬ments
#2. DictAdder, wit... |
import sqlite3
class Database:
def __init__(self,db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS std (id INTEGER PRIMARY KEY, usn TEXT, name TEXT, mobile INTEGER, branch TEXT)")
self.conn.commit()
def insert(self,us... |
import sys
wyrazenie_lista = []
nawias_l = []
OPERATORY = ('+', '-', '*', '%')
POZ_OPER = (('*', '%'), ('-'), ('+'))
def main():
print("\t\t\t\t\t PROSTY KALKULATOR")
print("""
Ten prosty kalkulator wykonuje podstawowe operacje:
- mnożenie;
- dzielenie modulo;
- dodawanie;
- odejmowanie
... |
# conda_python3_code
from tkinter import *
def callback():
print (u"你好~")
def popup(event):
menubar.post(event.x_root,event.y_root)
root = Tk()
menubar=Menu(root)
menubar.add_command(label="撤销",command=callback)
menubar.add_command(label="重做",command=root.quit)
frame=Frame(root,width=300,height=300)
frame.... |
# conda_python3_code
from tkinter import *
from PIL import Image,ImageTk
# PIL is used for decode the JPG PNG format
# Clear text display
# def show():
# print('Your name is %s'% e1.get())
# print('Your id is %s'% e2.get())
# root = Tk()
#
# Label(root,text='name:').grid(row=0,column=0)
# Label(root,text='ID... |
# conda_python3_code
from tkinter import *
# panedwindow is the advanced func of pack.
# showhandle means the control line of panedwindow
m1 = PanedWindow(showhandle=True,sashrelief=SUNKEN)
m1.pack(fill=BOTH,expand=1)
left = Label(m1,text="left pane")
m1.add(left)
m2 = PanedWindow(orient=VERTICAL,showhandle=False,s... |
from array import array
array_num = array('i', [4,3,6,3,1,2,2,3,3])
print("Original array: "+str(array_num))
print("Number of occurrences of the number 3 in the said array: "+str(array_num.count(3))) |
#numberlist = ['1','5','8','3']
#value1 = True
numberlist = list(input("Please Enter numbers "))
numbers = input("Please Enter number ")
if numbers in numberlist:
print("True")
else:
print("False")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.