text stringlengths 5 121k |
|---|
nameList = ['小明','terry','angel']
print(len(nameList))
print(nameList[1])
nameList.append('jerry')
print(nameList)
nameList.insert(1,'Jack')
print(nameList)
nameList.pop()
print(nameList)
nameList.pop(1)
print(nameList)
print([x * x for x in range(1, 11) if x % 2 == 0])
print([m + n for m in 'ABC... |
class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
f = [0] + flowerbed + [0]
for i in range(len(f)-2):
if f[i] == 0 and f[i+1] == 0 and f[i+2] == 0:
f[i+1] = 1
... |
"""
Created on Mon Jan 22 18:53:27 2018
@author: macbook
"""
class Solution:
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 0
if n % 2 == 0:
return self.integerReplacement(n//2)+1
else:
... |
"""
Created on Fri Jan 19 14:07:14 2018
@author: macbook
"""
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
class Solution:
"""
@param: root: The root of binary tree
@return: root of new tree
"""
def cloneTree(self, root):
... |
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
if not preorder:return None
res = TreeNode(preorder[0])
index = inorder.index(preorder[0])
left_in = inorder[:index]
... |
import textwrap
class Player:
def __init__(self, name, current_room, items=[]):
self.name = name
self.current_room = current_room
self.items = items
def get_name(self):
return self.name
def get_current_room(self):
return self.current_room
def __str__(sel... |
import matplotlib.pyplot as pyplot
def f(x):
return x + 1
def plot():
xs = list(range(-3,3))
ys = []
for x in xs:
ys.append(f(x))
pyplot.plot(xs, ys)
pyplot.show()
if __name__ == "__main__":
plot()
|
import sys
s = str(sys.argv[1])
print(s[::-1])
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('username', metavar='name', type=str, nargs='*',
help="Enter a name so the computer can say hello")
def hello(name):
print("Hello, {}!".format(name))
if __name__ == "__main__":
args = parser.parse_args()
hel... |
height = int(input("Enter a height: "))
width = int(input("Enter a width: "))
space = width - 2
for j in range(height):
if j == 0 or j == height - 1:
print("*" * width)
else:
print("*" + (" "*space) + "*")
|
mylist = []
for n in range(1,101):
Tnum = int(n*(n+1)/2)
mylist.append(Tnum)
print(mylist)
|
def catch_error():
while 1:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Enter an integer!")
except x == 3:
raise myError("This is not an integer!")
else:
x += 13
if __name__ == "__main__":
catch_error()... |
import matplotlib.pyplot as pyplot
def f(c):
return c * 9 / 5 + 32
def plot():
xs = list(range(-10, 40))
ys = []
for x in xs:
ys.append(f(x))
pyplot.plot(xs, ys)
pyplot.xlabel("Celsius")
pyplot.ylabel("Fahrenheit")
pyplot.show()
if __name__ == "__main__":
plot()
|
'''
Takes a paragraph as an input and returns a dictionary of the word count
'''
import sys
def histogram(스트링):
histo_dict = {}
words = 스트링.lower().split(" ")
for word in words:
try:
histo_dict[word] += 1
except KeyError:
histo_dict[word] = 1
retu... |
import train
import pretrain_STREAM
import sys
print("Which do you want to run ?")
print("train: 1, pretrain: 2")
x = input()
if x == "1":
train.main()
elif x == "2":
pretrain_STREAM.main()
else:
print("Please select 1 or 2")
sys.exit()
|
import sys
def check_duplicates(items):
list_items = items[:]
list_items.sort()
prev_item = None
for item in list_items:
if prev_item == item:
return True
else:
prev_item = item
return False
def create_unique_list(items):
unique_list ... |
import sys
from datetime import datetime
def check_subwords(word):
if len(word) == 1:
if word == "a" or word == "i":
return True
else:
return False
if word in reducible_words:
return True
status = False
sub_words = list()
for p... |
class Notifyer(object):
"""A simple class for handling event notifications"""
def __init__(self):
self.listeners = {}
def fireEvent(self, eventName, data = None):
"""Notifies all registered listeners that the specified event has occurred
eventName: The name of the event being fired
data: An optional param... |
INF = float("Inf")
n=7
d= [INF for c in range(n)]
c= [0 for c in range(n)]
nodes="sabcde"
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printGraph(self, dist):
... |
a = [5,15,-30,10,-5,40, 10]
def findMCS(a):
n = len(a)
S=[0 for i in range(n)]
for j in range(1, n):
S[j] = max(0, a[j] + S[j-1])
print ("S = ", S)
print("MCS =", max(S))
findMCS(a)
|
"""Module implements a Garch(1,1) model"""
import numpy as np
from scipy.optimize import minimize
class Garch:
"""Class implements Garch(1,1) model
Notes:
Conditional Maximum Likelihood Estimation is used to estimate
the parameters of Garch Model
todo - a two point estimation method for medium t... |
def countdown(num):
nums_list = []
for val in range(num, -1, -1):
nums_list.append(val)
return nums_list
def print_and_return(nums_list):
print(nums_list[0])
return nums_list[1]
def first_plus_length(nums_list):
return nums_list[0] + len(nums_list)
def values... |
from array import array
import matplotlib.pyplot as plt
def main():
avg = 0.0
samples = 0
values = []
alpha = float(input("IIR alpha (0..1.0): "))
if (alpha > 1.0):
print ('Setting alpha to 1.0')
alpha = 1.0
if (alpha < 0):
print ('Setting al... |
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9,10]
y = [35,32,20,14,3,30,6,20,2,30]
plt.plot(x, y)
plt.xlabel('busiest places in descending-order')
plt.ylabel('# of important customers')
plt.title('important_customers')
plt.show() |
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n // 10
return count
print(digits(25))
print(digits(144))
print(digits(1000))
print(digits(0))
|
import os
from datetime import date
import datetime
from os import path
def getDateTimeforFile():
now = datetime.datetime.now()
year = str('{:04d}'.format(now.year))
month = str('{:02d}'.format(now.month))
day = str('{:02d}'.format(now.day))
hrs = str('{:02d}'.format(now.hour))
minute = str('... |
class Solution:
def concatenatedBinary(self, n: int) -> int:
string = ""
def toBinary(num):
binVal = ""
while (num):
if (num & 1):
binVal += "1"
else:
binVal += "0"
num >>= 1
... |
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binarySearch(start, end, isLeft):
if (start > end):
return -1
mid = (start + end) // 2
if (target == nums[mid]):
if isLe... |
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
heapList = []
for index, listItem in enumerate(lists):
if listItem:
heapq.heappush(heapList, (listItem.val, index, listItem))
dummyHead = ListNode()
pr... |
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
prevNode = None
curNode = head
while(curNode.next != None):
nextNode = curNode.next
curNode.next = prevNode
prevNode = curNode
curNode = nextNode
curN... |
radius = int(input("what is the radius"))
print("what is the answer")
print(3.14*radius*radius)
|
import unittest
from city_function import city_country_name
class CityFunctionTest(unittest.TestCase):
"""Test for city_function.py"""
def test_city_function(self):
"""does 'Santiago, Chile' work?"""
formatted = city_country_name('santiago', 'chile')
self.assertEqual(formatted, 'Santiago, Chile')
def test_... |
aliens = []
for alien_number in range(30):
new_alein = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alein)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien[... |
while True:
try:
number1 = input("Please enter a number:(enter 'q' to quit) ")
if number1 == 'q':
break
number1 = int(number1)
number2 = input("Please enter another number:(enter 'q' to quit) ")
if number2 == 'q':
break
number2 = int(number2)
except ValueError:
print("You must enter a number")
... |
def cats_dogs_names(filename):
try:
with open(filename) as f:
pets_names = f.read()
except FileNotFoundError:
pass
else:
print(pets_names)
filenames = ['cats.txt', 'pig.txt', 'dogs.txt']
for filename in filenames:
cats_dogs_names(filename) |
from typing import *
from utils.tokenizing import *
TT_all = []
class TokenType:
"""A class that defines one type of token.
A token type has a name for debugging purposes, a regex to perform the check and a clean function called to e.g. remove
qotes from a string literal and unwrap the escapes.
... |
class queueusingstack:
def __init__(self):
self.__s1 = []
self.__s2 = []
self.__count = 0
def enqueue(self, data):
self.__s1.append(data)
self.__count += 1
def dequeue(self):
if self.isEmpty():
return -1
while len(self.__s1) != 1:
... |
def removeduplicates(string):
if len(string) == 0 or len(string)==1:
return string
if string[0] == string[1]:
smalleroutput = removeduplicates(string[1:])
return smalleroutput
else:
smalleroutput = removeduplicates(string[1:])
return string[0] + smalleroutput
print(re... |
def removeX(s, x):
if len(s)==0:
return s
smalllist = s[1:]
smalleroutput = removeX(smalllist, x)
if s[0]== x:
return smalleroutput
else:
return s[0] + smalleroutput
s = "axbxcx"
print(removeX(s, "x"))
|
class binarytree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printdetailtree(root):
if root == None:
return
print(root.data, end = ":")
if root.left != None:
print(root.left.data, end = ' ')
if root.right != None:
... |
class queue:
def __init__(self):
self.__data = []
self.__front = 0
self.__count = 0
def enqueue(self,item):
self.__data.append(item)
self.__count += 1
def dequeue(self):
if self.isEmpty():
return
ele = s... |
'''
@date: 2020-12-31
@author: Shell.Xu
@copyright: 2020, Shell.Xu <shell909090@gmail.com>
@license: BSD-3-clause
@comment:
translate srt to txt file
将srt文件转换为txt文件,容易阅读。
python3 srt.py [srt file]
'''
import sys
def read_multi_line(fi):
line = fi.readline().strip()
while line:
yield line
lin... |
import random
def random_number():
num1 = random.randint(1, 100)
return(int(num1))
random_number()
|
list = [1, 2, 3, 4, 5 ]
print(list[0], list[-1])
print(list[::2])
|
import random
options = ["rock", "paper", "scissors"]
computersChoice = random.choice(options)
print("Welcome to Rock, Paper, Scissors")
print("What do you choose?")
print(" ")
print("-----------------------------------")
playAgain = input("Ready to play? yes or no?")
while playAgain == "yes":
myChoice = input(... |
"""
An implementation of the Knuth-Morris-Pratt (KMP) string matching algorithm
The KMP algorithm spends a little time precomputing a table (on the order of the
size of W[], O(n)) and then uses the table to do an efficient search of the string
in O(k). KMP makes use of previous match information.
"""
def build_tab... |
"""
Given an array of integers that do not contain duplicate values,
determine if there exists any triplets that sum up to zero.
For example,
L = [-3, 2, -5, 8, -9, -2, 0, 1]
e = {-3, 2, 1}
return true since e exists
This solution uses a hash table to cut the time complexity down by n.
Time complexity: O(n^2)
Spac... |
"""
Given an array "nums" of n integers and an integer "target", find three integers in nums such that the sum is closest
to "target". Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closes... |
"""
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an MxN matrix,
return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals ar... |
"""
Given a sorted array of n integers that has been rotated an unknown number of times,
write code to find an element in the array. You may assume that the array was originally
sorted in increasing order.
"""
def find_in_rotated(key, rotated_lst, start, end):
"""
fundamentally binary search...
Either t... |
"""
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers num1 and num2, calculate the Hamming distance.
https://leetcode.com/problems/hamming-distance/
"""
def hamming_distance(num1, num2):
distance = 0
while num1 > 0 and nu... |
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is
used.
Note:
1. All letters in hexadecimal (a-f) must be in lowercase.
2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero
character... |
"""
Write a routine to convert a signed integer into a string.
"""
def integer_to_string(integer):
"""
Writes the string backward and reverses it
"""
if integer < 0:
is_negative = True
integer = -integer
else:
is_negative = False
integer_string = ""
while integer... |
def binary_search(sorted_list, left, right, key):
midpoint = (left + right) / 2
middle_element = sorted_list[midpoint]
if middle_element == key:
return "Key found at position: " + str(midpoint)
if right <= left:
return "Could not find element"
if key < middle_element:
retur... |
"""
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3, return [1,3,3,1]
Leetcode question: https://leetcode.com/problems/pascals-triangle-ii/
"""
def get_pascal_row(row_index):
"""Optimized for O(k) space"""
row = [0 for i in range(0, row_index + 1)]
for row_num in... |
"""
Given a positive integer, print the next smallest and the next largest number
that have the same number of 1 bits in their binary representation.
"""
def get_next_smallest(integer_value):
next_smallest = None
number_of_ones = count_ones(integer_value)
while integer_value != 0:
integer_val... |
"""
Given a non-negative integer number "num". For every numbers i in the range 0<=i<=num, calculate the number of 1's in
their binary representation and return them as an array.
Example:
For num = 5, you should return [0,1,1,2,1,2]
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(inte... |
"""
Write a method to randomly generate a set of n integers from an array of size
n. Each element must have equal probability of being chosen.
"""
import random
def pick_elements(original_list, number_of_elements, current_index):
if current_index == len(original_list):
return original_list[:number_o... |
"""
Write a method to return all subsets of a set
"""
all_subsets = [[]]
def get_all_subsets(original_set, n):
if n >= len(original_set):
return
new_subsets = []
for subset in all_subsets:
new_subset = []
new_subset.extend(subset)
new_subset.append(original_set[n])... |
"""
Write a method to count the number of 2s between 0 and n
"""
def number_of_twos(number):
count = 0
for i in range(2, number + 1):
count = count + get_number_of_twos(i)
return count
def get_number_of_twos(number):
count = 0
while number > 0:
if number % 10 == 2:
... |
"""
Implement a function that prints all possible combinations of the characters
in a string. These combinations range in length from one to the length of the
string. Two combinations that differ only in ordering of their characters are
the same combination. In other words, "12" and "31" are different combinations
... |
"""
Given two lines on a Cartesian plane, determine whether the two lines would
intersect.
"""
class Line:
def __init__(self, slope, yIntercept):
self.slope = slope
self.yIntercept = yIntercept
def intersect(line1, line2):
"""
If two different lines are not parallel, then they intersect... |
"""
Given a column title as appears in an Excel sheet, return its corresponding
column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Leetcode problem: https://leetcode.com/problems/excel-sheet-column-number/
"""
def title_to_number(column_title):
if column_title.strip() == '... |
"""
Given a positive integer, return its corresponding column title as it appears
in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
def convert_to_title(num):
integer_map = {}
characters = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
for i in range(0, 26):
integer_map[i] = c... |
from math import ceil
print("\n----------------------------------------")
print("AIR CONDITIONING MACHINE SELECTION - Adrià Bonjorn")
print("----------------------------------------\n")
ti=0
ns=0
tf=0
cf=0
ta=0
ca=0
st=0
ss=[]
ssa=0
nv="This value is not valid!"
def eval... |
import collections
import functools
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __... |
from matplotlib import pyplot
from Libreria1 import *
import math
def pot (matriz,exp):
for i in range (1,b):
res = multiMatrix(matriz,matriz)
return res
def experimentos(a, b, c):
r1 = pot(a,c)
r2 = Accion(r1,b)
return(res2)
def probabilidad (vector):
x,y = [],[]
for ... |
from bs4 import BeautifulSoup
def read_file():
file = open('three_sisters.html')
data = file.read()
file.close()
return data
soup = BeautifulSoup(read_file(),'lxml')
p = (soup.body.p)
for sibling in p.next_siblings:
print(sibling, sibling.name)
for sibling in p.previous_siblings:... |
from bs4 import BeautifulSoup
def read_file():
file = open('three_sisters.html')
data = file.read()
file.close()
return data
soup = BeautifulSoup(read_file(),'lxml')
a_tags = soup.find_all('a')
attr = {'class':'story'}
first_a = soup.find_all(attrs=attr)
print(first_a)
... |
import pandas as pd
import numpy as np
def data_cleaning(file_path):
column_name=["Customer Name","Customer ID","Customer Open Date","Last Consulted Date","Vaccination Type",
"Doctor Consulted","State","Country","Date of Birth","Active Customer"]
data=... |
""" Follows the work done on exceptions in the course: Core Python: Getting Started @
https://app.pluralsight.com/course-player?clipId=a8b1ac0f-c305-4505-a0d8-b40f4f858fcf """
import sys
from math import log
DIGIT_MAP = {
'zero': '0',
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five'... |
def vowelsremover(word):
vowels = ('a', 'e', 'i', 'o', 'u')
for i in word:
if i in vowels:
word=word.replace(i,'')
return(word)
|
from matplotlib import pyplot as plt
import random as rnd
import numpy as np
x = [0]
y = [50]
def flipping_fair(n_simulations = 50):
balance = 50
for i in range(n_simulations):
while 100 > balance and balance > 0:
coin = rnd.randint(1, 100)
if coin <= 50:
balance += 1
x.append(x[-1]+... |
from Data_Structures.linked_list import Linked_List
def merge_lists (list_a, list_b):
results = Linked_List()
if list_a.head == None:
return list_b
if list_b.head == None:
return list_a
a = list_a.head
b = list_b.head
results.head = a
if a == None:
results.head = b
if a != None... |
import gmaps
import numpy as np
def get_gmap_figure(LAT, LON, filename = 'apikey.txt'):
with open(filename) as f:
my_api_key = f.readline()
f.close
gmaps.configure(api_key=my_api_key)
center_of_all_sensors = (np.mean(LAT),np.mean(LON))
fig... |
import re
from utils import partition
def grep(pattern, filename):
"""Given a regex *pattern* return the lines in the file *filename*
that contains the pattern.
"""
return greplines(pattern, open(filename))
def greplines(pattern, lines):
"""Given a list of strings *lines* return the lines tha... |
from datetime import datetime, date
def organise_output(contents):
list_contents = list(contents)
for i, d in enumerate(list_contents):
line = '|'.join(str(item).ljust(80) for item in d)
if i == 0:
print('-' * len(line))
print(line)
def convert_to_date(date_string):
str... |
import unittest
from hw1 import *
class shoppingListTest(unittest.TestCase):
def testIsComplete_onePositiveQuantity(self):
self.assertFalse( is_complete([['cheese', 0], ['milk', 0], ['eggs', 12]]) )
def testIsComplete_allQuantitiesZero(self):
self.assertTrue( is_complete([['bread', 0],... |
import sys
for line in open(sys.argv[1]):
l = line.split()
lower = 0
upper = int(l[0])
for answer in l[1:]:
guess = lower + ((upper - lower + 1) // 2)
if answer == 'Lower':
upper = guess - 1
elif answer == 'Higher':
lower = guess + 1
else:
... |
import sys
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n%2 == 0 or n%3 == 0:
return False
if n < 25:
return True
for i in range(3, int(n**0.5)+1, 2):
if n%i==0:
return False
return True
from itertools import count
def g... |
import sys
month_name_to_number = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12)
def to_months(s):
month, year = s.split()
return (int(year) * 12) + month_name_to_number[month]
for line in open(sys.argv[1]):
months = 0
previous_end = 0
for start, end i... |
import sys
for line in open(sys.argv[1]):
n, p1, p2 = (int(x) for x in line.split(','))
print('true' if ((n >> (p1-1) & 1) == (n >> (p2-1) & 1)) else 'false')
|
import sys
for line in open(sys.argv[1]):
numbers = [int(x) for x in line.strip().split(',')]
max_ = sum(numbers)
for length in range(1, len(numbers), 2):
sum_ = sum(numbers[:length])
max_ = sum_ if sum_ > max_ else max_
for i in range(len(numbers)-length):
... |
from computer import Computer
import time
from collections import defaultdict
import math
def parse_input(filename):
with open(filename, 'r') as f:
return [int(n) for n in f.read().strip().split(',')]
def get_adjacent(x, y):
return [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]
def print_grid(grid)... |
if __name__ == '__main__':
print('n=')
n = int(input())
k = 0
for a in range(1, n):
for b in range(a, n):
for c in range(b, n):
if (c < a + b) and (a < b + c) and (b < a + c) and (a + b + c == n):
k = k+1
print(str(k) + ' treugolnikov')
|
"""Module 9-add_item
Adds all arguments to a Python list, and then save them to a file
"""
import sys
import json
save_to_json_file = __import__("7-save_to_json_file").save_to_json_file
load_from_json_file = __import__("8-load_from_json_file").load_from_json_file
filename = "add_item.json"
my_list = []
try:
m... |
def multiply_by_2(a_dictionary):
return {key: x * 2 for key, x in a_dictionary.items()}
|
"""
This module contains the matrix_divided function
"""
def matrix_divided(matrix, div):
"""
Divides all elements of a matrix. Returns a
new matrix (list of list). The result is
rounded to 2 decimal places.
"""
if not isinstance(matrix, list) or len(matrix) == 0 or not matrix[0]:
ra... |
"""
# http://codekata.com/kata/kata04-data-munging/
Part One: Weather Data
In weather.dat you’ll find daily weather data for Morristown, NJ for June 2002.
Download this text file, then write a program to output the day number (column one)
with the smallest temperature spread (the maximum temperature is the second colu... |
'''
print([num * 3 for num in range(3)])
print([num * 3 for num in range(10) if num % 2 == 0])
print([x * y for x in range(2, 10) for y in range(1, 10)])
'''
for i in range(5):
for j in range(5-i):
print('*', end='')
print("")
print('1번')
num = [1,2,3,4,5,6,7,8,9,10]
result = [n*2 for n in num i... |
def func(a,b,N):
c = a+b
N -= 1
if N == 0:
return 2*(c+b)+2*c
return func(b,c,N)
def solution(N):
if N == 1: return 4
if N == 2: return 6
return func(1,1,N-2)
print(solution(5))
print(solution(6)) |
class Node(object):
def __init__(self, key, data=None):
self.key = key
self.data = data
self.cnt=0
self.children = {}
class Trie(object):
def __init__(self):
self.head = Node(None)
def insert(self, string):
curr_node = self.head
for char in string:
... |
def solution(phone_book):
answer = True
pb= sorted(phone_book, key=lambda x: len(x))
for i in range(len(pb)-1):
for j in range(1, len(pb)-i):
if pb[i+j].find(pb[i]) == 0:
answer = False
break
return answer
a=['119', '97674223', '1195524421']
print(... |
def quick_sorted(arr):
if len(arr) > 1:
pivot = arr[len(arr) - 1]
left, mid, right = [], [], []
for i in range(len(arr)):
if arr[i] < pivot:
left.append(arr[i])
elif arr[i] > pivot:
right.append(arr[i])
... |
import re
str1 = input()
str2 = input()
str1 = re.sub('[^A-Za-z]+', '', str1)
str2 = re.sub('[^A-Za-z]+', '', str2)
str1 = list(str1)
str2 = list(str2)
len1 = len(str1)
len2 = len(str2)
s1 = []
s2 = []
gyo = 0
hap = 0
J = 0.0
def int... |
import random
import numpy as np
import matplotlib.pyplot as plt
class RandomPot:
def __init__(self, initval, maxspeed, mindif):
self.value = initval
self.maxSpeed = maxspeed
self.speed = 0
self.mindif = mindif
def calcnextval(self, target):
dif = target - self.value
... |
r=int(input())
for _ in range(r):
n=int(input())
x=input()
flag=False
for i in x:
if i!="N":
if i=="Y" :
ntn="NOT INDIAN"
if i=="I":
ntn="INDIAN"
flag=True
break
if (flag==False):
print("NOT SURE")
el... |
for i in range(int(input())):
x = int(input())
x -= 2
x = x//2
y = int(x*(x+1)/2)
print(y)
|
"""Module for working with median"""
from rand_data import get_rand_nums
def calc_median(nums):
"""Calculate the mean, given a list of numbers"""
sorted_nums = sorted(nums)
print(sorted_nums)
length = len(sorted_nums)
midpoint = length // 2
if (length % 2) == 1:
median = sor... |
import turtle
import time
import random
start = time.time()
t=turtle.Turtle()
t.hideturtle()
n = random.randrange(3,10)
RT = random.randrange(1,200)
L = random.randrange(10,100)
dL = random.randrange(10,100)
LT = RT-360/n
print('n={}'.format(n))
print('RT={}'.format(RT))
print('L={}'.format(L))
print('DL={}'.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.