text stringlengths 37 1.41M |
|---|
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
# edge case:
if not t:
return True
def check(s, t):
if not s:
return False
if s.val == t.val and dfs(s, t):
return True
return check(s.left, ... |
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.res = None
# self.cur = root
def dfs(r):
if not r:
return None
dfs(r.right... |
# 变种的200. 我没有做出来,思路是对的,用相对位置来记录island形状,但是没有implement出来,因为过于急躁,没有能够把思路整理清楚再修改。
# 这题的难点是把开始位置default成(0,0),这样直接完成位置记录,而不需要像我考虑的,是把所有绝对位置都拿到之后再计算相对位置。
class Solution:
def numDistinctIslands(self, grid: List[List[int]]) -> int:
shape = set()
h = len(grid)
w = len(grid[0])
def h... |
# 自己做出来的bfs
class Solution:
def shortestBridge(self, A: List[List[int]]) -> int:
# Step 1: find all edge nodes and save into queue
q = collections.deque()
lq = collections.deque()
dirs = [[1,0], [-1,0], [0,1], [0,-1]]
visited = set()
for i in range(len(A)):
... |
#This quiz has 3 levels easy, medium and harder and has to fill in the blanks to win it.
quiz_easy_answer = {'__1__':"website", '__2__':"web", '__3__':"Internet", '__4__':"LAN",'__5__':"URL"}
quiz_easy_para = """A __1__ is a collection of related __2__ pages, including multimedia content,
typically identified with a... |
# volidation for mobile number.
import re
regex=re.compile(r"\d(10)")
while True:
mobno=input("enther mobile no")
if len(mobno)==10:
result=regex.search(mobno)
if result:
print("valid mobileno")
break
else:
print("mobno should contain digits only")
... |
'''
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
In this article, Inheritance is introduced.
One of the major advantages of Object Oriented Programming is re-use.
Inheritance is one of the mechanisms to achieve the same.
In inheritance, a class (usually called superclass) is ... |
olcham=int(input("olchamni kiriting:"))
a=[[0]*olcham]*olcham
print(a)
for i in range(olcham):
for j in range(olcham):
a[i][j]= (input(f"a{[i]}{[j]}="))
print(a)
|
a=(1,2,3,4,5,6)
i=0
b=list(a)
c=[]
while i<(len(a)//2):
if i==0:
c.append(b[0])
else:
c.append(b[-i])
c.append(b[i])
i += 1
else:
c.append(b[i])
print(c) |
x=int(input("x="))
if x<-2 or x>2:
y=2*x
else:
y=(-3)*x
print(y) |
##################################################################
# FILE : torpedo.py
# WRITERS : Evyatar Cohan,Evyatar100,206121543 | Lior Paz,lioraryepaz,206240996
# EXERCISE : intro2cs ex9 2017-2018
# DESCRIPTION : contains class Torpedo
##################################################################
fro... |
def and_sets(*sets):
return sets[0].intersection(*sets[1:])
def or_sets(*sets):
return sets[0].union(*sets[1:])
def not_sets(*sets):
return sets[-1].difference(*sets[:-1])
def bool_set(operation,*sets):
'''combine ``sets`` with ``operation``
:and: combine sets with AND
:or: ... |
import random
from players.player import Player
class Game:
def __init__(self, word):
self.p1 = Player("David", "c")
self.p2 = Player("Rogers", "v")
self.game_word = word
self.subs = self.divide_strings_into_subs(self.game_word)
self.seperate_subs(self.subs)
def start(self):
self.p1.calculate_score(s... |
"""
Program to average the wind direction per day for each
day in a given month taken from data created by:
field_research_hweiss_v3.py
Written by Harrison Weiss
2018
"""
import xlrd
import xlwt
import sys
import json
class average:
m_day = 0
m_dir = 0.0
m_conut = 0
m_avg = 0
def write_default_... |
'''
Coded by Joanne Li, <joanne@caltech.edu>
The idea behind this strategy:
1) pick nodes that are all connected to each other in order to
create a sort of "super node" that will be able to resist
other players' advances by each voting for each other to keep
our team's color. start the search at the node with... |
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 its... |
# 942. DI String Match
# Easy
#
# 1159
#
# 446
#
# Add to List
#
# Share
# A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:
#
# s[i] == 'I' if perm[i] < perm[i + 1], and
# s[i] == 'D' if perm[i] > perm[i + 1].
# Given a string s, reconstruc... |
# 239. Sliding Window Maximum
# Hard
#
# 6351
#
# 246
#
# Add to List
#
# Share
# You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the
# array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by on... |
# Given a string s, find the length of the longest substring without repeating characters.
#
#
#
# Example 1:
#
# Input: s = "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:
#
# Input: s = "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Example ... |
# 300. Longest Increasing Subsequence
# Medium
#
# 7728
#
# 168
#
# Add to List
#
# Share
# Given an integer array nums, return the length of the longest strictly increasing subsequence.
#
# A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the
# order of the... |
# 206. Reverse Linked List
# Easy
#
# 6719
#
# 129
#
# Add to List
#
# Share
# Given the head of a singly linked list, reverse the list, and return the reversed list.
#
#
#
# Example 1:
#
#
# Input: head = [1,2,3,4,5]
# Output: [5,4,3,2,1]
# Example 2:
#
#
# Input: head = [1,2]
# Output: [2,1]
# Example 3:
#
# Input: h... |
# 264. Ugly Number II
# Medium
#
# 2637
#
# 160
#
# Add to List
#
# Share
# An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
#
# Given an integer n, return the nth ugly number.
#
#
#
# Example 1:
#
# Input: n = 10
# Output: 12
# Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the se... |
# 589. N-ary Tree Preorder Traversal
# Easy
#
# 900
#
# 63
#
# Add to List
#
# Share
# Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
#
# Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples... |
# 1306. Jump Game III
# Medium
#
# 1164
#
# 37
#
# Add to List
#
# Share
# Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
#
# Notice that you can n... |
# Pair Sums Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it
# which sum to k. If an integer appears in the list multiple times, each copy is considered to be different; that is,
# two pairs are considered different if one pair includes at least one array index whi... |
# 125. Valid Palindrome
# Easy
#
# 1970
#
# 3827
#
# Add to List
#
# Share
# Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
#
#
# Example 1:
#
# Input: s = "A man, a plan, a canal: Panama"
# Output: true
# Explanation: "amanaplanacanalpanama" is a palin... |
# 1249. Minimum Remove to Make Valid Parentheses
# Medium
#
# 2084
#
# 48
#
# Add to List
#
# Share
# Given a string s of '(' , ')' and lowercase English characters.
#
# Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return... |
# 1041. Robot Bounded In Circle
# Medium
#
# 1234
#
# 348
#
# Add to List
#
# Share
# On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
#
# "G": go straight 1 unit;
# "L": turn 90 degrees to the left;
# "R": turn 90 degrees to the right.
# The rob... |
import nltk
from nltk import pos_tag, word_tokenize, tokenize
from nltk import FreqDist
from nltk.tokenize import sent_tokenize
# All words average
def lexical_diversity(text):
return len(text) / len(set(text))
# Percentage of text taken over by one word
def percentage(count, total):
return 100 * count / tota... |
def hangaroo(secretWord):
intro = str(len(secretWord))
lettersGuessed = []
guess = str
mistakesMade = 10
wordGuessed = False
print ('Welcome to Hangaroo!')
print ('Guess a word that is ',intro,' letters long.')
print ('_______________________________________________________... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
def plot_class_histograms(inputs, targets, bins=20, colors=None, ax=None):
"""
Plots histograms of 1d input data, split according to class
parameters
----------
inputs - 1d vector of input values (array-like)
t... |
import numpy as np
import pandas as pd
def import_from_csv(ifname, input_cols=None, target_col=None, classes=None):
"""
Imports the iris data-set and generates exploratory plots
parameters
----------
ifname -- filename/path of data file.
input_cols -- list of column names for the input data
... |
import random
def generate_training_sets(num_sequences=10, num_train_sets=100):
"""Generate training data. Returns list of sequences."""
return [
[build_random_sequence() for i in range(num_sequences)]
for i in range(num_train_sets)
]
def build_random_sequence():
"""Build a random se... |
import pygame
import button as bt
import Main as mn
class Display_Info(object):
""" Class describing a device object and relevant """
All = []
def __init__(self, init_x, init_y, name = "Not Defined", setpoint = 0, unit = ' '):
"""Add self to list of all objects"""
self.All.append(self)
"""Initialize variab... |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._
#
# ... |
import pandas as pd
#Read csv
df = pd.read_csv('read_file.csv')
print(df.col5)
# group by column5 Same as value counts
print(df.groupby('col5').col5.count())
#Min value of col3 for each name
print(df.groupby('col5').col3.min())
#group by multiple columns
print(df.groupby(['col5','col1']).col3.min())
#agg method -> ... |
import csv
import csv_funcs
import pandas as pd
from radiodata import RadioData
"""
This is the function that will produce the
CSV which will be used to generate the dataloss
queue.
"""
# This is the main function of the Radio-to-CSV script.
# It writes the data given by a RadioData object into a CSV fi... |
class employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
# self.email = f"{self.fname + self.lname}@gmail.com"
@property
def email(self):
if self.fname is None or self.lname is None:
return "Email Is Not Given"
ret... |
# lambda is also used to create function in one line
a = lambda x,y: x-y #before : x,y we have to put value in it
print(a(5,3))
|
"""
This Code Is Developed By Kuldeep Saini
My Instagram:- https://www.instagram.com/kuldeep_saini_65
This Is A Guess Game Of 2 Players. Both Player Must Guess A Correct Number In Less Chances then Other Player
Language Used:- Python
I Used Basic Python Concept To Build This Game
"""
from random import r... |
class students:
no_of_leaves = 400
def __init__(self, name, std, rollno): # Constructor
self.name = name
self.std = std
self.roll_no = rollno
def details(self):
print(f"Name = {self.name} \nstd = {self.std} \nRoll NO = {self.roll_no}")
@classmethod
def... |
# To Understanding this must Watch Video #55 self init
class students:
def __init__(self, name, std, rollno): # Constructor
self.name = name
self.std = std
self.roll_no = rollno
def details(self):
print(f"Name = {self.name} \nstd = {self.std} \nRoll NO = {self.roll_no... |
from time import sleep
#1
#checking Result For class !2th
name1 = ["Kuldeep","Lovish","Paras","Harman","Rahul"]
user_result = input("Enter Your First Name:- ").capitalize()
if (user_result in name1):
print("Congratulations! ")
else:
print("Oops! Get Lost You fool")
#We can also use "not in "functio... |
from Newton import *
from scitools.std import *
f = lambda x: x**6 * sin(pi*x)
df = lambda x: 6*x**5 * sin(pi*x) + x**6 * pi * cos(pi*x)
x0 = sort([-2.6, -1.2, 1.5, 1.7, 0.6])
for i in x0:
x, info = Newton(f, i, df, epsilon=1e-13, N = 100, store=True)
# we assume convergence for this exercise
info = transpose(info... |
def s(M):
'''computes the harmonic series up to, but not including, the Mth term'''
sum = 0
for i in range(1,M):
sum += 1.0/i
return sum
x = 1.0/1 + 1.0/2
print '1/1 + 1/2 = %.3f \ns(3) = %.3f' % (x,s(3))
'''
python sum_func.py
1/1 + 1/2 = 1.500
s(3) = 1.500
'''
|
def trapezoidal(f, a, x, n):
from scitools.std import array, iseq, linspace, zeros
x = array(x)
I = zeros(len(x))
index = 0
new_sum = 0
old_sum = 0
for i in x:
new_sum = 0.5*f(a)
h = (i-a)/float(n)
new_sum += sum(f(a + array(range(1,n))*h))
new_sum += 0.5*f(i)
new_sum *= h
new_sum += old_sum
I[inde... |
def findPrimes(N):
'''
Uses sieve of Eratosthenes to find all primes between 1 and N, inclusive
'''
a = [1]*(N+1)
p = []
for i in range(2,N+1):
if a[i] == 1:
p.append(i)
j = 2*i
while j <= N:
a[j] = 0
j += i
return p
N = 100
p = findPrimes(N)
print 'Primes less than or equal to', N, 'are...'
for ... |
def v(r, beta, mu0, R, n):
'''
Computes the velocity of a fluid through a long pipe
R is the radius of the pipe
r is the radius at which we measure fluid flow (0 <= r <= R)
n is a real number reflecting the viscous properties of the fluid
beta is the pressure gradient
mu0 is a viscosity coefficient
'''
return ... |
# simulate the sum() function
list = [1, 3, 5, -5]
sum = 0
for i in list:
sum += i
print 'sum of', list, 'is %d' % (sum)
'''
python sum.py
sum of [1, 3, 5, -5] is 4
'''
|
def substance1(filename):
'''
Parses a data file to create a dictionary
of the names of substances and their densities
'''
density = {}
infile = open(filename, 'r')
for line in infile:
words = line.split()
key = ' '.join(words[:-1])
density[key] = float(words[-1])
infile.close()
return density
def subst... |
from math import pi
g = 9.81 # m/s**2, acceleration due to gravity
rho = 1.2 # kg/m**3, density of air
a = 11 # cm, the radius of the area of the football normal to the
# velocity vector
A = pi * (a/100.)**2 # m**2 cross section of football
m = .43 # kg, mass of football
C_D = 0.2 # drag coefficient
v1 = 120 # k... |
from binomial_distribution import binomial
print '''The probability of getting two heads from five coin flips
is %.2f%%''' % (100*binomial(2,5,.5))
print '''The probability of getting four ones in a row when throwing
a die is %.2f%%''' % (100*binomial(4,4,1./6))
print '''The probability of a skier experiencing a ski b... |
def fact(n):
prod = 1
if n != 1 and n != 0:
while n > 1:
prod *= n
n = n-1
return prod
print 'Our function computes 4! = %d' % (fact(4))
from math import factorial
print 'As a check, 4! = %d' % (factorial(4))
'''
python fact.py
Our function computes 4! = 24
As a check, 4! =... |
q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
for i in q:
for j in range(len(i)):
print i[j]
'''
python nested_list_iter.py
a
b
c
d
e
f
g
h
'''
|
# calculate interest rate
A = 1000 # euros, our principal
n = 3 # years
p = 5 # percent interest rate
money = A * (1 + p/100.)**n
print """After %d years with an apr of %d, our principal of %d euros
has grown to %.2f euros.""" % (n, p, A, money)
'''
After 3 years with an apr of 5, our principal of 1000 euros
has gr... |
"""
https://leetcode.com/problems/reverse-nodes-in-k-group/
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k:... |
#!/usr/bin/env python
"""
Given a sequence [1, 2, ..., N], there is one element missed,
find the missed number
"""
def missing_num(arr, last):
total_XOR = 0
arr_XOR = 0
for i in range(1, last + 1):
total_XOR ^= i
for j in arr:
arr_XOR ^= j
return total_XOR ^ arr_XOR
if __... |
#!/usr/bin/env python
def sum_count(arr, index, total):
if total == 0:
return 1
if total < 0:
return 0
if index < 0:
return 0
if arr[index] > total:
return sum_count(arr, index - 1, total)
return sum_count(arr, index - 1, total) + sum_count(arr, index - 1, total -... |
#! /usr/bin/env python
"""
microsoft interview question, find the lowest common ancesstor of two nodes in
a binary tree.
"""
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def find_path_to_node(root, node, path):
i... |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) < 2:
return s
# change the s to odd length
s1 = "*"
for c in s:
s1 += c
s1 += "*"
index = 1
strLengt... |
"""
https://leetcode.com/problems/unique-paths-ii/
"""
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
m = len(obstacleGrid)
n = len(obstacleGrid[0])
matrix = [[0] * n for _ in range(m)]
matrix[0][0] = 1 - obstacleGrid[0][0]
print matrix
for i in ... |
"""
https://leetcode.com/problems/climbing-stairs/
@date: 2021-08-25
"""
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
a, b = 1, 2
for i in range(0, n - 2):
a, b = b, a + b
return b
if __... |
"""
https://leetcode.com/problems/search-insert-position/
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target < nums[0]:
return 0
if target > nums[-1]:
... |
"""
https://leetcode-cn.com/problems/merge-k-sorted-lists/
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=Non... |
#! usr/bin/python3
###########################
#### GENERATORS ####
###########################
tupla = (x for x in range(19))
#print(tupla)
#print(next(tupla))
#print(next(tupla))
def funzione_generatore():
yield('Uno')
yield('Due')
yield('Tre')
yield('Quattro')
#print(funzione_generatore)... |
#!/usr/bin/python
############################
### FOR ###
############################
# Possiamo iterare liste, set, dizionari, tuple
#frutta = ['mela','pera','banana']
#frutta = {'mela','pera','banana'}
#frutta = ('mela','pera','banana')
#frutta = {0:'mela',1:'pera',2:'banana'}
#for x in frutta.... |
#!/usr/bin/python
################################
#### IF...ELSE ####
################################
var1 = 100
if var1:
print ("1 - La condizione è VERA")
print(var1)
else:
print ("1 - La condizione è FALSA")
print(var1)
var2 = 0
if var2:
print ("1 - La condizione è VERA")
print(va... |
##########
# LV Marlowe
# 09/15/2020
# Grade Converter
# This program converts a grade percentage into a letter grade.
# Assume that fractions .5 and above are rounded up, fractions .4 and below are rounded down, and grade percentages below 0 are impossible.
##########
# Ask for user's grade percentage.
per... |
##########
# LV Marlowe
# 09/15/2020
# Number Guessing Game
# This program plays a number guessing game with the user.
##########
# Select random number from 0 to 9.
from random import randint
randomNum = randint(0, 9) # integer
# Ask user to guess number from 0 to 9.
guess = input('I\'m thinking of ... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 00:34:11 2020
@author: dilayerc
"""
import numpy as np
# Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive).
# Afterwards use Boolean indexing to pick out only the odd numbers in the array
# Create a 5 x 5 ndarray with consecutiv... |
from turtle import *
speed(-1)
shape("turtle")
color("green")
for j in range(36):
for i in range(360):
forward(1)
left(1)
right(10)
mainloop() |
tudien = {
"ck": "Chồng",
"vk": "vợ",
"p": "bạn"
}
while True:
print("*"*20)
for k in tudien:
print(k, end="\t ")
print()
user = input("Your code? ")
if user in tudien:
print("Translation: ", tudien[user])
else:
anw = input("Not found, do you want to contrib... |
import datetime
now = datetime.datetime.now()
time = now.year
year = int(input("Ban sinh nam bao nhieu?"))
age = time - year
# print("tuoi cua ban la", age )
if age < 10:
print("Baby")
elif age <= 18:
print("Teenager")
else:
print("Not Baby")
print("Bye")
|
print(2+3)
print(2-3)
print(2*3)
print(2/4) # This gives answer in fraction
print(4/2) # This gives 2.0
print(4//2) # This gives 2 beacuse it is integer division
print(2//4) # This gives 0 beacuse it is integer division
print(11//3) # This gives 3 beacuse it is integer division
print(6%2) # Th... |
# Infinite loop by mistake
i=1
while i<=10:
print("Hello World")
# Forgot to give increment i.e i+=1
# press Ctrl+C to stop this while running
# Use of infinite loop by us
while True:
print("Hello World") |
import sys
def SortAndRotated(arr, n):
minEle = sys.maxsize
maxEle = -sys.maxsize - 1
minIndex = -1
for i in range(n):
if arr[i]< minEle:
minEle = arr[i]
minIndex = i
flag1 = 1
for i in range(1, minIndex):
if arr[i] < arr[i - 1]:
flag1 = 0
break
flag2 = 2
for i in range(minIndex + 1, n... |
#!/usr/bin/env python
# coding: utf-8
# ### Syntax:
#
# <pre>
# class x:
# statements
#
# class z(<b>x</b>):
# statements
#
# class z will inherit all the properties and behaviours from class x
# </pre>
# In[8]:
class A:
x = 6
def my_fun(self):
print("class A")
class B:
y = 7
def... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 13:51:27 2020
To test the class and functions
"""
import unittest
import Sample_Test as s
class TestAdd(unittest.TestCase):
"""
Testing Sample_Test module
Test runner observes the code and find out the method starts with test.
It will be run those... |
from abc import ABCMeta, abstractmethod
from enum import Enum
class CoinEnum(Enum):
Y100 = 0
Y500 = 1
class Coin(metaclass=ABCMeta):
@abstractmethod
def no(self):
pass
@abstractmethod
def value(self):
pass
class Y100(Coin):
def no(self):
return CoinEnum.Y100
... |
import re
#定义获取超链接的函数
def get_url(html):
urls = re.findall('href=.*?>', html) # 正则出a链接 href
urlList = [] # 定义urlList
for url in urls:
url = url.replace("href=\"", '') # 替换href="
urlList.append(url[:-2]) # 获取的0到-2长度的字符串
print(urlList)
#字符串信息
html1 = '''<h3>contact us</h3>
<p>contact... |
char = input("Your customized character: ")
print(char, char, '', sep=char)
print(char, sep='')
print(char, char, '', sep=char)
print(char, ' ', char, sep='')
print(char, char, '', sep=char)
|
def User(name,passw):
names=[{'name':'jhon','passw':'2345kdd','usertype':1},
{'name':'zkz','passw':'0725abc','usertype':2},
{'name':'wxj','passw':'0829wxj','usertype':6},
{'name':'jhon','passw':'2345kdd','usertype':9}]
for line in names:
if line['name']==name and line... |
"""
2. Context manager.
Реализуйте контекстный менеджер timer, используя __enter__ и __exit__
Check yourself:
with timer('doing some sleeps'):
time.sleep(1)
time.sleep(2)
time.sleep(3)
Output:
timer: block 'doing some sleeps' executed in 6.013 sec
"""
from time import perf_counter, sleep
clas... |
#!/usr/bin/env python
def comprobar():
a = raw_input("dame un numero: ")
b = raw_input("dame otro numero y te dire si el primero es multiplo del segundo: ")
try:
if int(a) % int(b) == 0:
print (a + " es multiplo de " + b)
else:
print (a + " no es multiplo de " + b)
except:
print("No has introducido dos ... |
"""
Complete the method/function so that it converts dash/underscore delimited words into camel casing.
The first word within the output should be capitalized only if the original word was capitalized (aka Pascal Case).
Examples:
to_camel_case("the-stealth-warrior") # returns "theStealthWarrior"
to_camel_case("The_S... |
"""
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed
(Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than
one word is present.
"""
def spin_wo... |
import numpy as np
from _run_life import run_life
def life(n=20, plot=False):
"""Set up the board and start the simulation"""
# Fill the board randomly (but with a known seed for repeatability)
np.random.seed(1)
board = [[np.random.randint(0, 2) for i in range(n)] for j in range(n)]
####### DON'T ... |
from enum import Enum
import random
class Suit(Enum):
Spade = "S"
Heart = "H"
Club = "C"
Diamond = "D"
class Value(Enum):
Two = "2"
Three = "3"
Four = "4"
Five = "5"
Six = "6"
Seven = "7"
Eight = "8"
Nine = "9"
Jack = "J"
Queen = "Q"
King = "K"
Ac... |
print('enter the value range\n')
marks=int(input())
for num in range(marks):
if(num%3==0 and num%5==0):
print('fizzbuzz')
elif(num%3==0):
print('fizz')
elif(num%5==0):
print('buzz')
else:
print(num)
"""""
n=int(input())
sum=sum(range(1,n))
print(sum)
"""
"""""
#adding t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def bserach(dataList, n, value): # 二分查找递归实现
'''
注意:
1、dataList中不能出现重复元素。
2、如果只查询dataList中是否出现value值,是可以出现重复值的。
时间复杂度:
O(logn)
空间复杂度:
O(1)
'''
def bserachTemp(dataList, startIndex, endIndex, value):
if startInde... |
def encrypt(text,shift): #performs encryption using caeser cipher
encrypted_text=""
for i in text:
if (i.isupper()):
encrypted_text += chr((ord(i) + shift-65) % 26 + 65)
else:
encrypted_text += chr((ord(i) + shift - 97) % 26 + 97)
return encrypted_text
def decrypt(text,shift): ... |
# Profit Calculator
# 24 Sept 2018
# CTI-110 P2T1 - Sales Prediction
# Palti Kerr
#
# Get the porjected total sales.
total_sales = float(input('Enter the projected sales: '))
# claculate the porfit as 23 percent of total sales.
profit = total_sales * 0.23
#Display the porfit.
print ('The profit is $', f... |
''''
Create dictionary
The countries and capitals lists are again available in the script. It's your job to convert this data to a dictionary where the country names are the keys and the capitals are the corresponding values. As a refresher, here is a recipe for creating a dictionary:
my_dict = {
"key1":"value1",
... |
'''
Import a file in chunks
When working with large files, it can be easier to load and process the data in pieces. Let's practice this workflow on the Vermont tax data.
The first 500 rows have been loaded as vt_data_first500. You'll get the next 500 rows. To do this, you'll employ several keyword arguments: nrows and... |
import numpy as np
from typing import Mapping, Dict, List, Union
from fractions import Fraction
def assign(input): #TODO docstring; typing
"""
Calls the assignment method required by an assignment input JSON and returns the output the method produces. Assumes
the input is validated.
"""
votes ... |
#!/usr/local/bin/python3
class Dog:
species = "Canis Familiaris"
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
def __str__(self):
return f"{self.name} is a {self.age} years old {self.breed}."
x = ''
while x != 'no':
... |
#!/usr/local/bin/python3
number = 17
def print_formatted(number):
spaces = (len((bin(number).replace("0b", "")))) + 1
for i in range(number):
num = i + 1
octal = oct(i + 1).replace("0o", "")
hexal = hex(i + 1).upper().replace("0X", "")
binary = bin (i + 1).replace("0b", ""... |
#!/usr/local/bin/python3
# a + 1 == b
# a + 2 == c
# A + 1 == B
string_name = "I Don't Like"
def swap_case(string_name): # Defining fucnction named swap_case with string_name variable/input
ret = '' # Defining ret
for element... |
# task 1.0 - init
import csv
FILENAME = "names.csv"
FILE_START_YEAR = 1895
START_YEAR = 1950
END_YEAR = 2013
def read_lines():
with open(FILENAME, newline='', encoding="utf8") as file:
reader = csv.reader(file)
lines = []
for line in reader:
if line != "":
... |
"""Simple tests for the components; use the notebook for the actual cases
"""
import longitudinal
import numpy as np
import csv
def rescale(x, min, max):
"""Rescale a numpy array (x - min) / (max - min)
Input:
x: A numpy array
min: New floor (likely less than or equal to min(x))
max: New ceiling (likely great... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.