text stringlengths 37 1.41M |
|---|
class DSU:
def __init__(self, lst):
self.values = lst
self.len = len(lst)
self.parents = list(range(self.len))
def find_set(self, x):
if self.parents[x] == x:
return x
self.parents[x] = self.find_set(self.parents[x])
return self.parents[x]
def is... |
class A:
value = 13
def some_method(self):
print(f"Method in A, value = {self.value}")
class B(A):
def some_method(self):
print(f"Method in B, value = {self.value}")
class C(B):
value = 6
def some_method(self):
print(f"Method in C, v... |
class Planet():
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return f'Planet {self.name}'
earth = Planet('Earth')
print(earth.name)
print(earth)
solar_system = []
planet_names = [
'Mercury', 'Venus', 'Earth', 'Mars'... |
class Descriptor:
def __get__(self, obj, obj_type):
print('get')
def __set__(self, obj, value):
print('set')
def __delete__(self, obj):
print('delete')
class Class:
attr = Descriptor()
instance = Class()
# instance.attr
# instance.attr = 10
# del instance.attr
class Desc... |
anna = {'name': 'Anna',
'age': 35,
'cats':True,
'beard': False,
'hair_color': 'pink'}
ryan = dict(anna)
ryan['beard'] = True
ryan['hair_color'] = 'Brown'
ryan['name'] = 'Ryan'
ryan['cats'] = 'Nope!'
print(ryan)
print(anna)
class Person(object):
def __init__(
self, na... |
from sys import argv # import function from sys module
script, filename = argv
# line 1 to 3 uses argv to get filename
txt = open(filename) # here open file
print "Here are your file %r:" % filename # little message
print txt.read() # read file
txt.close() # added after stduy drill
print "Type the filename again:" # ... |
# B351/Q351 Spring 2019
# Professor Saúl Blanco
# Do not share these assignments or their solutions outside of this class.
#################################
# #
# Assignment 1: Python Methods #
# #
#################################
import math
############... |
class Node(object): #объявили класс "Узел"
def __init__(self, contained_object, next): #Конструктор
self.contained_object = contained_object
self.next = next
class MyQueue(object): #объявили класс "Очередь"
def __init__(self): #конструктор изначально пустой очереди
self.head = None #нач... |
""" Abstracts the process of converting the output from the requests
into more workable json objects
"""
class OutputHandler(object):
def __init__(self):
import json
self.json = json
""" Turns a object into the string form of a json and returns it as
a beautified json
... |
# Code your solution here
string = input("Enter a string")
print(string.swapcase()) |
marks = input('User Grade')
if marks >=35
print("Passing grade")
else:
print("Failing Grade")
|
'''
Look at the main function for testing the queue
'''
class queue:
def __init__(self):
self.inStack = []
self.outStack = []
def enqueue(self, x):
self.inStack.append(x)
def dequeue(self):
if len(self.inStack) == 0 and len(self.outStack) == 0:
raise Exception('Queue is empty')
if len... |
f = open("zedd.txt")
for line in f:
line = line.rstrip()
if not "is" in line:
continue
print(line)
|
import sqlite3
class User:
def __init__(self, _id, username, password):
self.id=_id
self.username=username
self.password=password
@classmethod
def find_by_username(cls, username):
connect = sqlite3.connect('data.db')
cursor = connect.cursor()
query="select ... |
# -*- coding: utf-8 -*-
def write_to_pickle(filename, list_of_sentences):
import cPickle as pickle
f = open("%s.pickle"%filename, "wb")
pickle.dump(list_of_sentences, f)
f.close()
print "The data was saved to %s.pickle. The file contains %d lines."%(filename, len(list_of_sentences))
def... |
# Crie um programa que leia quanto dinheiro uma pessoa tem na
# carteira e mostre quantos Dolares ela pode comprar.
print('--== Desafio 010 ==--')
n = float(input('Digite o valor em reais: '))
r = n / 3.27
print('É possivel comprar ${:.4f}'.format(r)) |
# Faça uma programa que leia o nome de um pessoa e mostre uma
# mensagem de boas-vendas.
print('--== Desafio 002 ==--')
nome = input('Qual seu nome ? ')
print('Olá ',nome,', Prazer em Conhece-lo!')
|
# Faça um programa que leia o nome completo de uma pessoa. mostrando
# o primeiro e o ultimo nome separadamente.
print('--== Desafio 027 ==--')
nome = str(input('Digite seu nome completo: ')).strip().split()
print('Seu primeiro nome é {}\nSeu ultimo nome é {}'.format(nome[0], nome[len(nome)-1])) |
import numpy as np
import sys
try:
escagno = int(input("¿Cuántos escaños se reparten? "))
numPartidos = int(input("¿Cuántos partidos se presentan a las elecciones? "))
except ValueError:
print("No es un número")
sys.exit(-1)
listaPartidos = []
for _ in range(0, numPartidos):
partido = dict()
... |
import numpy as np
import sys
try:
rows = int(input("Introduzca el número de filas: "))
cols = int(input("Introduzca el número de columnas: "))
except ValueError:
print("No es un número")
sys.exit(-1)
matrix = np.random.rand(rows, cols)
print("Los valores de la matriz son")
print(matrix)
print("El ... |
#
# El formato del fichero será el siguiente:
# En la primera línea, separado por un espacio
# se pondrá el número de filas y columnas
# Cada fila del fichero será una fila de la matriz
# Cada elemento estará separado por un espacio
#
import numpy as np
import sys
if len(sys.argv) != 2:
print("Se ha llamado mal a... |
import time
def iinput(showstring,default):
ttemp = input(showstring)
if ttemp == "":
return default
else:
return ttemp
def fastdivision(value):
A = ((value + D) * mult) >> N
return A
def getsizeof(value):
sizeof = 0
while value:
value >>= 1
sizeof += 1
... |
class Node:
def __init__(self,data,next):
self.data=data
self.next=next
'''
def printlist(sourceList):
printnode=sourceList
if sourceList==None:
print('printnode-None')
else:
while printnode.next != None:
print('printnode',printnode.data,end=" ")
... |
# 7. Write a program which accept one number and display below pattern.
# Input : 5
# Output : 1 2 3 4 5
# 1 2 3 4 5
# 1 2 3 4 5
# 1 2 3 4 5
# 1 2 3 4 5
#
def fun(num):
for i in range(1,num+1):
for j in range(1,num+1):
print(i ,end=" ")
print("\r")
print("Enter row");
num=int(input(... |
# 8 Write a program which accept one number and display below pattern.
# Input : 5
# Output : 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
def fun(num):
for i in range(1,num+1):
for j in range(1,i+1):
print(j,end=" ")
print("\r")
print("Enter Num-:");
num=int(input());
fun(num)
... |
# 1.Write a program which contains one function named as Fun(). That function should display
# “Hello from Fun” on console.
def fun():
print("Hello from Fun");
fun()
# Output-:
# zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1
# $ python fun.py
# Hello from Fun
|
# 3. Write a program which contains one class named as Numbers.
# Arithmetic class contains one instance variables as Value.
# Inside init method initialise that instance variables to the value which is accepted from user.
# There are four instance methods inside class as ChkPrime(), ChkPerfect(), SumFactors(),
# F... |
# 1.Design python application which creates two thread named as even and odd. Even
# thread will display first 10 even numbers and odd thread will display first 10 odd
# numbers.
import threading
def even(no):
for i in range(1,no):
if(i%2==0):
print("Even",i);
def Odd(no):
for i in range(1,no)... |
# 6.Write a program which accept number from user and check whether that number is positive or
# negative or zero.
# Input : 11 Output : Positive Number
# Input : -8 Output : Negative Number
# Input : 0 Output : Zero
print("Enter num");
num=int(input())
if num > 0:
print ("Positive Number");
elif num == ... |
# 2.Write a program which contains one lambda function which accepts two parameters and return
# its multiplication.
# Input : 4 3 Output : 12
# Input : 6 3 Output : 18
fptr=lambda no1,no2:no1*no2;
no1=int(input("Enter Fist number-:"));
no2=int(input("Enter Second number-:"));
ans=fptr(no1,no2);
prin... |
# Write a program which display first 10 even numbers on screen.
# Output : 2 4 6 8 10 12 14 16 18 20
def fun(num):
for i in range(2,num*2+2,2):
print(" ",i);
num=int(input())
fun(num)
# Output-:
# zine@DESKTOP-BU1PSC0 MINGW64 ~/Desktop/python/Ass1
# $ python even_num.py
# 10
# 2
# 4
# 6... |
#!/usr/bin/env python
#some eg of mathematical functions
import math;
x=int(input('enter any no. to calculate factorial: '));
fact = math.factorial(x);
print('factorial of given no. : ',fact);
# print('pi value: ', math.pi)
|
# author: h.serimer 03.2021 https://github.com/eproje/uPy_Course
# Board: Lolin32 Lite
# simple touch
# There are ten capacitive touch-enabled pins that can be used on the ESP32: 0, 2, 4, 12, 13 14, 15, 27, 32, 33.
# Trying to assign to any other pins will result in a ValueError.
# REF: https://docs.micropython.org/en/... |
import time
import machine
from machine import Pin
Led1=Pin(22, Pin.OUT)
Led2=Pin(23, Pin.OUT)
def YakSondur(pinNo,sure,tekrar):
for i in range (tekrar * 2 ):# kitap sayfa 73
pinNo.value(1 - pinNo.value()) # toogle değerin tersini alır
time.sleep(sure)
try:
#program çalışırken yapılacak işle... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################
# File name : p.py
# Create date : 2018-07-23 08:49
# Modified date : 2018-07-23 13:04
# Author : DARREN
# Describe : not set
# Email : lzygzh@126.com
#####################################
# class TreeNode:
# def __init__... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################
# File name : p.py
# Create date : 2018-07-23 08:49
# Modified date : 2018-07-23 13:04
# Author : DARREN
# Describe : not set
# Email : lzygzh@126.com
#####################################
class Solution:
def __init__(sel... |
x= 8
# if x < 2:
# print('samll')
# elif x < 10:
# print('medium')
# else :
# print('large')
#=======================================
sh = input('enter your working hours: ')
sr = input('enter rate: ')
fh = float(sh)
fr = float(sr)
#. print(sh, sr)
if fh > 40 :
print('Overtime')
reg = fr * fh
... |
import math
def CountSplitInversion(left_array, right_array):
left_len = len(left_array)
right_len = len(right_array)
array = []
i = 0
j = 0
count = 0
for k in range(left_len + right_len):
if i == left_len:
array += right_array[j:right_len]
break
if ... |
# -*- encoding: utf-8 -*-
__metaclass__ = type
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print "Aaaah..."
self.hungry = False
else:
print "No, thanks!"
class SongBird(Bird):
def __init__(self):
s... |
# -*- encoding: utf-8 -*-
def init(data):
data['first'] = {}
data['middle'] = {}
data['last'] = {}
def lookup(data, label, name):
"""look for full names in dicitionary"""
return data[label].get(name)
def store(data, full_name):
"""
store people\'s full names
hello world
"""
n... |
# Author @dan
# facebook : /whodanyalahmed
# twitter : /whodanyalahmed
# instagram : @whodanyalahmed
# linkedin : /in/whodanyalahmed
import math
while True:
print("\n\t\tVector")
print("\t\t------\n")
print("1 - Dot (.) Product")
print("2 - Length")
print("3 - Unit Vector")
print("4 - Vector ... |
import time
import threading
import random
from multiThreading.error import ThreadSafeQueueException
class ThreadSafeQueue(object):
"""
创建一个线程安全的队列类
"""
def __init__(self, max_size=0):
self.queue = []
self.max_size = max_size
self.lock = threading.Lock()
self.conditio... |
#Rosalind_countdna
#Objective: Count each nucleotide in a given sequence
'''DNA strand is composed of 4 different nucleotides A,C,G,T. This task will
perform how to count nucleotides in a sequence using python'''
import os
os.chdir('/home/vu/Downloads') #move to a desired directory
f = open('rosalind_dna (1).txt', 'r... |
from datetime import datetime
# Current date time in local system
date = datetime.now().date()
date = str(date)
print("Todays Date:",date)
enterDate = input("Enter date in format shown above ({0}):".format(date))
if(enterDate == ""):
enterDate = date
fileName = str("presentPeople"+enterDate+".txt")
# try:
# ... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@staticmethod
def inorder(node):
if node is None:
return
TreeNode.inorder(node.left)
print(node.val)
TreeNode.inord... |
# 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 inorder(self, root, sum):
if root is None:
return
self.stack.append(root.val)
self.inorder(... |
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if __name__ == '__main__':
sudoku = [['53..7....'],
['6..195...'],
['.98....6.'],
... |
class Solution:
# @param {string[]} tokens
# @return {integer}
def evalRPN(self, tokens):
if not tokens:
return 0
stack = []
for t in tokens:
try:
val = int(t)
stack.append(val)
except ValueError:
if ... |
# 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 kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
... |
# coding: utf-8
# Tools to study different variations of the the somma cube
# ----------------------------------
# ---------------------------------
# In[1]:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Rotation, shifting and transposition of 2D--shapes
# -------------------------------... |
import numpy as np
def forward_euler_step(deriv, t, u, dt):
return u + dt * deriv(t, u)
def forward_euler(deriv, init, time_min, time_max, numSteps):
'''
Solves a differential equation using Euler's method from time_min to
time_max, using a step of time_step
deriv: callable; the derivative
in... |
"""nota1 = int(input("ingrese la primera nota: "))
nota2 = int(input("ingrese la segunda nota: "))
nota3 = int(input("ingrese la tercera nota: "))
prom=(nota1+nota2+nota3)/3
if prom>=7:
print("promocionado")
elif prom>=4:
print("regular")
else:
print("reprobado")
x=1
suma=0
while x<=10:
valor=int(in... |
lista = []
for k in range(10):
lista.append(input("agregue valor a la lista: "))
print("los elementos de la lista son:"+str(lista))
valor=int(input("introduce el valor a modificar pon el indice:"))
nuevo=input("ingresa el nuevo valor:")
lista[valor]= nuevo
print("los elementos de la lista son:" +str(lista))
valor=... |
class TvProgram:
def __init__(self, name, year):
self._name = name.title()
self.year = year
self._likes = 0
def __str__(self):
return f'Name: {self._name} - Year: {self.year} - Likes: {self._likes}'
@property
def likes(self):
return self._likes
@property
... |
#! /usr/bin/env python
import Card
import HandEvaluation as he
class Hand:
""" A Hand of Poker cards """
def __init__(self, handId):
self.cardNumbers = []
self.handId= handId
self.suitCountDict = {Card.Card.HEARTS : 0, Card.Card.DIAMONDS : 0, Card.Card.SPADES : 0, Card.Card.CLUBS : 0}
self.faceCo... |
#! /usr/bin/env python
import random
import Card
class Deck:
""" A Deck of Poker cards"""
_DECK = range(0, 52)
def __init__(self, size):
#self.numericCardValues = range(0, 52)
#random.shuffle(self.numericCardValues)
self.numericCardValues = random.sample(self._DECK, size)
self.nCardsDealt = 0... |
import random
minimum = int(raw_input("Lowest number in range: "))
maximum = int(raw_input("Highest number in range: "))
number = random.randint(minimum, maximum)
statement = "Guess a number between " + str(minimum) + " and " + str(maximum) + ": "
guess = int(raw_input(statement))
tries = 0
while guess != number:
if... |
import streamlit as st
import gspread as gsp
import pandas as pd
from df2gspread import df2gspread as d2g
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
# Authorising the code with the client key
credentials = ServiceAccountCredentials.from_json_keyfile_name('... |
from collections import namedtuple
Datapoint = namedtuple('Datapoint', ['attributes', 'label'])
def attributes(dataset):
'''
Return an iterator of the attributes in the dataset.
'''
for p in dataset:
yield p.attributes
def labels(dataset):
'''
Return an iterator of the labels in the d... |
from tkinter import *
import math
class calc:
def getandreplace(self):
self.expression = self.e.get()
self.newtext = self.expression.replace('/', '/')
self.newtext = self.newtext.replace('x', '*')
def equals(self):
self.getandreplace()
try:
sel... |
import cv2
import numpy as np
# This file is about intensity transformation in a image.
# I will use three functions for that, negative to show a negative imagem,
# e logarithmic and exponential to increase or decrease the constrast.
img = cv2.imread("pout.tif", 0)
#img = cv2.imread("negative.jpeg") #Colorful Image
... |
def number_in_range(low, high, number):
if(low < number and high > number):
return True
else:
return False
number1= 1
number10 = 10
number_in_the_range = 4
number_out_range = -5
number_too_high = 100
isnumberinrange = number_in_range(number1, number10, number_in_the_range)
print(isnumberinra... |
'''
Problem 1
'''
people = int(input("How many people are attending to the campfire?"))
if (people == 1):
print("Just you then?")
if (people == 2):
print("Bring marshmellows, please")
if (people >= 3):
print("More than 3 is a crowd")
if(people >= 7):
print("Party")
if (people < 0):
print("Which dime... |
print("Give me a number")
number = input(">")
factors_list =[]
for x in range(1, int(number) + 1):
if (int(number) % x == 0):
factors_list.append(x)
print(number,"has",len(factors_list),"factors, ","which are", factors_list)
|
"""
problem 1
"""
x = 5
y = 5.9
z = True
w = "62"
"""
problem 2
"""
a = float(input("please enter a number for a"))
A_t = ((3**1 / 2) /4) * a
A_s = a**2
b = .25
c = 5**(1/2)
d = 5 * (5 + 2 * c)
A_p = b * (d**(1/2)) * (a**2)
print(" The area of the pentagon is " + str(A_p))
print(" The area of the triangle is " + str(... |
import math
top = 20
def is_prime(x):
if x == 2:
return True
if x % 2 == 0:
return False
for y in xrange(3, int(math.sqrt(x)) + 1, 2):
if x % y == 0:
return False
return True
def power_trip(x):
if x * x > top:
return x
y = 2
while x ** y <= top:
y += 1
return (x ** (y - 1))
def main(x):
n = 1
... |
## 没有必须要求掌握,难度较大,如果是刚开始学习Python的同学,可以先跳过,一个月以后再回来看
##1.理解闭包函数定义
##2.理解闭包函数的调用
##3.变量在不同函数中的作用域
# 闭包函数
# 函数定义
name = "鲸鱼"
def func1():
print("我是func1")
print(name)
# 在函数func1 内在定义一个函数
def func2():
name = "虾米"
print("我是func2")
print(name)
# 返回"肚子"里面的函数对象
return func2
# 不加... |
import random as r
import math
class Map:
def __init__(self, width, height, min_size = 10, max_size = 40, generate = True):
if(min_size>max_size):
raise OverflowError("Map minimum size cannot be greater than maximum size")
self.width = width
self.height = height
self.rooms = []
self.min_s... |
# crypto.py
# --------------
# COMP1405A - Fall2020
## Student: Queenie Li
## ID: 101185786
def encrypt(message, shift, alphabet):
result = ""
for x in range(0,len(message)):
for y in range(0,len(alphabet)):
if message[x] == alphabet[y]:
shift_position = y + shift
... |
nums = [1, 2, 3, 4, 5]
words = ['one', 'two', 'three', 'four', 'five']
d = dict(zip(nums, words))
print(d)
print(type(d))
d1 = {}
for i, val in enumerate(nums):
d1[val] = words[i]
print(d1)
print(type(d1))
def listtodict(list1, list2):
return dict(max(vars(__builtins__).items())[1](list1, list2))
d3 = li... |
from collections import deque
class Stack:
def __init__(self):
self.stack=deque()
def push(self,data):
self.stack.append(data)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def empty(self):
... |
class Multiples:
global numberOfMultiples
global multiplier
global multiplicand
def MultiplesInARange(self, multiplier, numberOfMultiples):
multiplicand=1
multipleslist = list()
while(multiplicand<numberOfMultiples):
product=multiplier*multiplicand
... |
from tkinter import *
def click(event):
text = event.widget.cget("text")
print(text)
if text == "=":
if scvalue.get().isdigit():
value = int(scvalue.get())
else:
try:
value = eval(screen.get())
except EXCEPTION as e:
prin... |
# coding: utf-8
# タプルを用いて公約数を求めるプログラム
# 順序型と多重代入の利用
def findDivisors (n1, n2):
"""n1とn2を正のint型とする。
n1とn2のすべての公約数からなるタプルを返す"""
divisors = ()
for i in range(1, min(n1, n2) + 1):
if n1 % i == 0 and n2 % i == 0:
divisors = divisors + (i,)
return divisors
def findExtremeDivisors(n... |
# -*- coding: utf-8 -*-
# *幾何分布*
# 幾何分布は指数分布を離散化したものである
# それは最初の成功までの必要な独立試行の回数を表す
import random
import pylab
def successfulStarts(eventProb, numTrials):
"""eventProb : 一回の試行で成功する確率を表す浮動小数点数
numTrials : 正の整数
各実験において,成功するまでに必要な試行の回数を出力する"""
triesBeforeSuccess = []
for t in range(numTrials):
... |
# coding: utf-8
# 様々なソート
## 選択ソート
## 計算量O(n^2) インプレースなので外部記憶は定数サイズ
def selSort(L):
"""Lを、>を用いて比較できる要素からなるリストとする
Lを、昇順にソートする"""
suffixStart = 0
while suffixStart != len(L):
#サフィックスの各要素を見る
for i in range(suffixStart, len(L)):
if L[i] < L[suffixStart]:
#要素を入れ替え... |
def withdraw_money(current_balance, amount):
if (current_balance >= amount):
current_balance = current_balance - amount
else:
print("Insufficnet funds")
return current_balance
def add2 (number):
output = number + 2
return output
answer = add2(3)
print("The answer is: ", answer)
##... |
'''
Source Name: label.py
Author: Brandon McLellan
Last Modified: August 7th, 2012
Last Modified By: Brandon McLellan
Description:
Revision History:
Revision 3:
- Added easy way of mass-updating options.
Revision 2:
- Overhauled label options
Revisi... |
#22/123
L = ['michael','sarah','tracy','bob','jack']
print(L)
print([L[0],L[1],L[2]])
r = []
n = 3
for i in range(n):
r.append(L[i])
print(r)
print(L[0:3])
print(L[:3])
print(L[1:3])
print(L[-2:])
print(L[-2:-1])
L = list(range(100))
print(L)
print(L[:10])
print(L[-1... |
#23/123
d = {'a':1,'b':2,'c':3}
for key in d:
print(key)
for value in d.values():
print(value)
for k,v in d.items():
print(k,v)
for ch in 'ABC':
print(ch)
from collections import Iterable
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
print(isi... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} x
# @return {ListNode}
def partition(self, head, x):
if not head or not head.next:
return... |
class Solution:
# @param {integer} dividend
# @param {integer} divisor
# @return {integer}'
def divide(self, dividend, divisor):
if dividend == -1*math.pow(2,31) and divisor==-1:
return int(math.pow(2,31)-1)
result = 0
flag = -1
rem = abs(dividend)
tmp... |
class Solution:
# @param {string} s
# @return {integer}
def lengthOfLastWord(self, s):
if len(s)==0:
return 0
result = ""
for i in range(len(s)):
if s[-1-i]!=" ":
result+=s[-1-i]
elif len(result)!=0:
break
re... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
if headA is None or headB is None:
... |
# 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 boolean
def hasCycle(self, head):
if not head:
return False
s,f = ListNode(0),head
... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
import heapq
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
# write yo... |
import sqlite3
from sqlite3 import Error
import datetime
from math import pi, acos, cos, sin
#! ***** MENU *****
def menu():
linha(40)
print('--- MENU ---')
linha(40)
print('1- Criar db')
print('2- Criar tabelas')
print('3- Insere dados')
print('4- Atualizar dados')
print('5- Selecion... |
class Player:
def __init__(self, name, symbol):
self.name = name
self.symbol = symbol
class Game:
MAX_STEPS = 9
DEFAULT_SYMBOL = "_"
def __init__(self):
self.player_1 = Player("Игрок 1", "X")
self.player_2 = Player("Игрок 2", "O")
self.current_step = 0
... |
#!/usr/bin/python3
'''
module containing the recurse function
'''
import requests
def recurse(subreddit, hot_list=[]):
'''
function that recursively finds a list of all hot topics of a subreddit
Attributes:
subreddit - subreddit to find hot topics of
hot_list - list to store to... |
import abc
import hashlib
from typing import Tuple
MINIMAL_LENGTH_OF_SECURITY_STRING = 3
class PasswordRepository(abc.ABC):
def __init__(self, username_hash_salt: str):
PasswordRepository.verify_security_string_length(username_hash_salt, MINIMAL_LENGTH_OF_SECURITY_STRING,
... |
class Cat:
def eat(self):
print("%s is eating"%self.name)
def drink(self):
print("it is drinking")
tom = Cat()
tom.name="TOM"
tom.eat()
print(tom)
addr=id(tom)
print("十进制is %d\n" %addr)
lazy_cat=Cat()
lazy_cat.name="大懒猫"
lazy_cat.eat()
|
while i<(len(lst)):
if type(lst[i]) ==type([]):
round_list(lst[i],decimals)
elif type(lst[i]) == [type(0.0),type([])]:
i+=1
else:
list1[i]=round(list1[i],decimals)
i+=1
|
import numpy as np
def get_mean(num_1, num_2):
"""Функция возвращает медианное число типа int из двух заданных"""
mean = int(np.mean(range(num_1, num_2 + 1))) # поиск медианного числа
return mean # возвращает медианное число
def game_core_v3(number):
"""Угадывает путем называния медианного числа с... |
def file_reader():
arr = []
file = open("file .txt", "r") # File called data.txt must be in the same directory as the number_of_times.py
# Read each line from the file
for line in file:
list = line.split()
# Read each word from a line
for word in list:
arr.append(word) # Add each word... |
# Python3 has 5 built-in sequence types:
# > string
# > list
# > tuple
# > range
# > bytes and bytearray
# What is a sequence?
# An ordered set of items
# "Hello world"
# ["PC", "Speakers", "Keyboard", "Mouse"]
# Because a sequence is ordered, we can use indexing to access individual items in the sequence
# Almost e... |
def fibonacci(n: int) -> int:
"""
Return `n`th Fibonacci number for a positive value of `n`.
The value of the number at position n in the Fibonacci equence is determined by:
F[n] = F[n - 1] + F[n - 2]
where: F[0] = 0 and F[1] = 1
"""
prev = 0
current = 1
if 0 <= n <= 1: ... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
... |
class Solution(object):
def isPalindrome(self, x):
if x < 0 or (x%10 == 0 and x > 0):
return False
rev = 0
carry = -1
num = x
temp = []
while num is not 0:
temp.append(num % 10)
carry += 1
num = num // 10
while c... |
import urllib.request, json
with urllib.request.urlopen("https://canlidoviz.com/borsa.jsonld") as url:
data = json.loads(url.read())
a = data["mainEntity"]["itemListElement"]
for i in a:
b = i["currentExchangeRate"]
print("{} = {}".format(i["currency"],b["price"]))
... |
n = int(input("Enter Integer : "))
a = 0
for val in range(0,(n+1)) :
a += (val/((val+1)))
print(a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.