text stringlengths 5 121k |
|---|
from __future__ import print_function
"""
hgrep.py regexp file-name
(poor man's breadcrumb context)
Output matching lines with paths to root in outline hierarcy.
Displaying one line for each immediate parent (less indent than current)
The lines are displayed in the format
right-indented-line-number:line-including t... |
class Contact(object):
def __init__(self, first_name, last_name, email, phone):
self.first = first_name
self.last = last_name
self.email = email
self.phone = phone
def show(self):
return "%s, %s - %s (%s)" % (self.last, self.first, self.email, self.phone)
|
class Bird:
def fly(self):
print("Bird fly with their wings")
class Airplane:
def fly(self):
print("Airplane fly fuel")
class Baloon:
def fly(self):
print("Baloon can fly in air with the help air")
l=[Bird(),Airplane(),Baloon()]
for i in l:
i.fly()
|
class A:
def __init__(self,a=None,b=None):
if a!=None and b!=None :
print(" u enter two parameter")
elif a!=None:
print("u enter single parameter")
else:
print(" no argument pass")
a=A()
a=A(2,3)
a=A(5)
|
num=int(input("Enter a no:"))
sum1=0
totaldig = 0
while num>0:
rem = num % 10
sum1 += rem
num //= 10
totaldig += 1
print("Som of the total digits are :",sum1)
print("Total Digits are :",totaldig)
|
l=[]
eve=[]
odd=[]
n=int(input("How many no u wants add in list :"))
for i in range(n):
a=int(input("Enter Numbers :"))
l.append(a)
for i in l:
if i%2==0:
eve.append(i)
else:
odd.append(i)
print("----Statements----\n" \
"1.List elemets--\n" \
"2.Display Even no on lis... |
l=[-1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,2]
n=0
for i in l:
n=n+1
print("total no in list :",n)
|
class employee:
def __init__(self,empid,empname,sal,city):
self.empid=empid
self.empname=empname
self.sal=sal
self.city=city
emp=employee(101,"bhushan",600000,"yavatmal")
emp1=employee(102,"xyz",500000,"pune")
print(emp.empid)
print(emp.empname)
print(emp.sal)
print(emp.city)
print(emp1.empid)
print(emp1.empn... |
'''
7.Given a list,
l = ['cat','dog','dow','sheep']
Make the first character of words into capital.
'''
l = ['cat','dog','dow','sheep','cjc']
l2=list(map(lambda a:a.title() ,l))
print(l2)
result3 = list(filter(lambda x: (x == "".join(reversed(x))), l))
print(result3)
|
class Student:
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
l=[]
n=int(input("enter no. do u want to add"))
for i in range(n):
s=Student(int(input("Enter rollno :")),input("Enter name :"))
l.append(s)
li=tuple(l)
for stud in li:
print(stud.rollno)
print(stud.name)
print(type(li)... |
def m1(age):
print("m1---")
if age<0:
raise ArithmeticError("age Problem")
print("m1----end")
try:
m1(-6)
except ArithmeticError as e :
print("except block",e)
print("program end")
|
'''
4.Replace a word by another word in a file.
'''
f=open("testfile.txt","r")
a=f.read()
replace_word=a.replace("word","hello")
f.close()
f=open("testfile.txt","w")
f.write(replace_word)
f.close()
f=open("testfile.txt","r")
print(f.read())
f.close()
|
n=int(input("Enter any no :"))
print("Table of Numer ",n)
for i in range(1,11):
print(n,"x",i,"=",n*i) |
'''
2.Program to display particular line taken by user.
'''
f=open("bhushan.txt","r")
b=f.readlines()
print(b)
a=int(input("which line no u want see :"))
print(b[a-1])
f.close()
|
'''
1.Below are the two lists convert it into the dictionary
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
'''
k = ['Ten', 'Twenty', 'Thirty']
v= [10, 20, 30]
d={}
d=dict(zip(k,v))
print(d)
d2={k[i]:v[i] for i in range(len(k))}
print(d2)
|
'''
5.Given a dictionary, swap the key-value
d = {0:'a',1:'b',2:'c'}
Expected output:
{'a':0,'b':1,'c':2}
'''
d = {0:'a',1:'b',2:'c'}
d2={v:k for k,v in d.items()}
print(d2)
|
class A:
a=10
def m1(self):
print("m1.......A")
class B(A):
def m1(self):
print("m1.......B")
super().m1
class C(A):
def m1(self):
print("m1.......C")
super().m1()
a=C()
a.m1()
b=B()
b.m1()
print(C.__mro__)
|
from abc import ABC,abstractmethod
class A(ABC):
@abstractmethod
def m1(self):
pass
@abstractmethod
def m2(self):
pass
def m3(self):
print("m3----A")
class B(ABC):
@abstractmethod
def m3(self):
print("m1-----B")
@abstractmethod
de... |
a=10
b=20
def add():
print(a+b)
def sub():
print(a-b)
def mul():
print(a*b)
add()
sub()
mul()
|
from student import *
print("----Statements----\n" \
"1.Enter details--\n" \
"2.display--\n" \
"3.Exit--\n")
while True:
ch=int(input("Enter Your choice----:"))
if ch<=2:
pass
if ch==1:
l=[]
n=int(input("How many student details u want to insert ... |
def squre(func):
def inner(args):
x = func(args)
return x*x
return inner
def multiply(func):
def inner(args):
x = func(args)
return x*2
return inner
@multiply
def num(no):
return no
n=int(input("Enter a number :"))
print(num(n))
|
class employee:
def __init__(self,empid,empname,sal,city):
self.empid=empid
self.empname=empname
self.sal=sal
self.city=city
def showemp(self):
print("Employee ID :",self.empid)
print("Employee Name :",self.empname)
print("Salary :",self.sal)
print("city :",self.city)
if __name... |
from cal2 import *
print("----Statements----\n" \
"1.Addition--\n" \
"2.Subtraction--\n" \
"3.Multiplication--\n" \
"4.Exit--\n")
while True:
ch=int(input("Enter your Choice"))
if ch<=3:
x=int(input("Enter First no"))
y=int(input("Enter Second no"))
if ch==1:
s=add(x,y)
print("Addi... |
a=30
b=20
def add():
c=a+b
print(c)
def sub():
c=a-b
print(c)
def mul():
c=a*b
print(c)
def div():
c=a/b
print(c)
def expo():
c=a**2
print(c)
def mod():
c=a%b
print(c)
def floor():
c=a//b
pr... |
from threading import Thread
import time
class Testing(Thread):
def __init__(self,st,end):
super().__init__()
self.st=st
self.end=end
def run(self):
for i in range(self.st,self.end,2):
time.sleep(0.5)
print(i)
time.sleep(0.5)
odd = Tes... |
'''
multiple except block
'''
try:
print("start try block")
a=int(input("Enter a Value"))
print(10/a)
print("end try block ")
except (ValueError,ZeroDivisionError)as msg:
print("plz Enter valid value",msg)
|
from emp import *
print("----Statements----\n" \
"1.Enter details--\n" \
"2.display--\n" \
"3.Exit--\n")
while True:
ch=int(input("Enter Your choice----:"))
if ch<=2:
pass
if ch==1:
a=int(input("Enter Employee ID:"))
b=input("Enter EMP Name :")
c=int(input("Enter salary :"))
d=input... |
class Student:
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
def __str__(self):
return "Student Roll no :{} and Student Name :{}".format(self.rollno,self.name)
eng=set()
comp=set()
mech=set()
n=int(input("How many student u want add for comp :"))
for i in range(n):
s1=Student(int(input("E... |
from banco import Banco
class Usuarios(object):
def __init__(self, idusuario=0, nome="", telefone="", email="", usuario="", senha=""):
self.info = {}
self.idusuario = idusuario
self.nome = nome
self.telefone = telefone
self.email = email
self.usuario = usuario
... |
import matplotlib.pyplot
import math
file = open("myfile.txt",'r')
wordkinds = 0
words = 0
tedadkalamatmotefavet = {}
kalamat = []
for line in file:
for word in line.split():
words = words + 1
if(word not in kalamat):
kalamat.append(word)
wordkinds = wordkinds +... |
'''
批量重命名,会删除原来的文件!!!,使用前注意备份,命名会自动补零
'''
import os
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='batch rename')
parser.add_argument('--dir', dest='dir', help='file directory',default='None')
parser.add_argument('--name', dest='name', hel... |
import random
def sort_word(word):
head = word[0]
tail = word[len(word) - 1]
l = list(word)[1:len(word)-1]
random.shuffle(l)
return head + "".join(l) + tail
str1 = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
ret = []
for w ... |
print ("Basic conditional instructions\n")
def even(a):
if ((a % 2) == 0):
print (a, "is even")
if (a == 0):
print (a, " == 0")
return True
else:
print (a, "is odd")
return False
even(5)
even(6)
even(0)
bln = even(6)
if bln:
print ("6 is even")
... |
"""
How to use unittest
execution:
python test_random.py
or
python -m unittest discover
"""
import random
import unittest
class RandomTest(unittest.TestCase):
""" Test case for random """
def test_choice(self):
"""
given: a list
when: selecting a random elt
... |
print ("Object management")
class Whiteboard:
"""
A whiteboard simulator"""
def __init__(self):
self._surface = ""
def write(self, str):
if self._surface != "":
self._surface += "\n"
self._surface += str
def display(self):
return sel... |
import unittest
from user import User
class TestUser(unittest.TestCase):
def setUp(self):
self.new_user = User('leskey', 'levy', 'leskeylevy@gmail.com', 'Nairobi')
def test_init(self):
'''
test to see if object isproperly initialised
'''
self.assertEqual(self.new_user... |
'''
This is a script to construct the Barnsley fern, a fractal discovered by mathematician Michael Barnsley.
Due to its 'flexible' nature, in that by changing the hyper-parameters you can construct different ferns,
the structure is classified as a super-fractal!
The script works by iteratively applying one of four lin... |
def feeder(meal, amount):
if meal == "Breakfast":
print ("Hopper1," * amount)
elif meal == "Lunch":
print ("Hopper2," * amount)
elif meal == "Dinner":
print ("Hopper1 ,Hopper2 ," * amount)
feeder("Lunch", 100000000 ) |
class Stack:
def __init__(self):
self.stack=list()
def push(self,value):
self.stack.append(value)
def pop(self):
if len(self.stack)<1:
print ("Stack is empty")
else:
self.stack.pop()
def printStack(self):
print(self.stack)
stack=Stack... |
import numpy as np
import pandas as pd
x = pd.DataFrame({'a':[1,2,3,4,5],'b':[20,20,30,40,50]})
x
a = x.columns
print(a)
x.index
x['b'].sum()
def inc(x):
x=x+100
return x
x['b'].apply(inc)
x.sort_values('b')
x['b'].unique()
x['b'].nunique()
x[... |
my_number = 52
def guessnumber():
user_number = input ("Guess my number: ")
if int(user_number) == my_number:
print("Good job! You guess the right number")
print("Game over")
elif int(user_number) > my_number:
print("You number is too high")
guessnumber()
else:
print("Your number is too low")
guessn... |
from graphsTrees.trees.node import Node
class Tree:
def create_node(self,key):
return Node(key)
def insert(self, node, key):
if node is None:
return self.create_node(key)
else:
node.left = self.insert(node.left, key)
return node
def sear... |
from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\\Users\\brkre\\Ram\\Selenium\\geckodriver.exe")
driver.maximize_window()
driver.get("https://rahulshettyacademy.com/#/index")
print(driver.title)
print(driver.current_url)
driver.get("https://rahulshettyacademy.com/#/mentorship... |
import unittest
import fizz_buzz
class Test_fizz_buzz(unittest.TestCase):
def test_number(self):
self.assertEqual(fizz_buzz.fizz_buzz(1),1)
def test_fizz(self):
self.assertEqual(fizz_buzz.fizz_buzz(3),'Fizz')
self.assertEqual(fizz_buzz.fizz_buzz(42),'Fizz')
def test_b... |
import numpy as np
n=np.random.randint(1,101)
guess,small,big=(0,1,100)
while n!=guess:
guess=int(input(f"從{small}到{big}猜個數字吧"))
if guess > big or guess <small:
print(f"超出範圍啦,從{small}到{big}猜個數字吧")
else:
if guess > n:
print("太大囉!")
big=guess
elif guess < n :
... |
def run():
global paddle_vel,ball_pos,move_unit
if (ball_pos[-1][0]-ball_pos[-2][0]) <0:
print("ball moves left")
if (ball_pos[-1][1]-ball_pos[-2][1]) >0:
print("ball moves down")
paddle_vel=move_unit
elif (ball_pos[-1][1]-ball_pos[-2][1])<0:
print("ball moves up")
paddle_vel=-move_unit
else:
... |
for h in range(1,25):
for m in range(1,60):
for s in range(1,60):
print(h,":",m,":",s)
|
def suma_de_matriz(matriz):
suma=0
for i in matriz:
suma+=sum(i)
return(suma)
def tablero():
matriz=[]
for i in range(10):
matriz.append([0]*10)
return(matriz)
def posbarcos(jugador1):
for k in range(4):
while True:
fila=int(input("Ing... |
def fibonacci(n):
if n<2:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
n=int(input("puesto en la sucesion de fibonacci "))
print(fibonacci(n))
|
def duplicatenumber(n, m, duplList):
for num in range(n,m):
currentnum = num
count = 0
for x in duplList:
if currentnum == x:
count += 1
if count == 2:
return currentnum
dupList = list(range(100))
dupList[23] = 22
dupnumber = duplicatenumbe... |
"""Customers at Hackbright."""
class Customer(object):
"""Ubermelon customer."""
def __init__(self, first, last, email, password):
self.first_name = first
self.last_name = last
self.email = email
self.password = password
def __repr__(self):
return "<Custome... |
hrs = input("Enter Hours:")
rt = input("Enter rate:")
hrsf = float(hrs)
rtf = float(rt)
pay = hrsf*rtf
print("Pay:",pay)
|
"""
Created on Tue May 16 12:48:37 2017
@author: PULKIT LUTHRA
"""
import random
board=[]
for i in range(9):
board.append(-1)
def drawBoard():
print(' | |')
print(' ' + str(board[0]) + ' | ' + str(board[1]) + ' | ' + str(board[2]))
print(' | |')
print('------... |
'''
Print the following pattern for the given N number of rows.
Pattern for N = 4
1
11
202
3003
Input format :Integer N (Total no. of rows)
Output format :Pattern in N lines
Sample Input :5
Sample Output :
1
11
202
3003
40004
'''
num=int(input('Enter the num for pattern : '))
for i in range(1,num+1):
for j ... |
loop = 0
while True:
loop += 1
message = input("\nPlease enter your age: \n")
if message == 'quit':
print (str(loop))
break
else:
if (int(message) < 3):
print("\nYour ticket is free! \n")
elif(3<=int(message)<=12):
print("\nYour ... |
valdict = {
"variable": "Elementar data type that stores values",
"loop": "Self repeating structure",
"dictionary": "Glossary structure",
"array": "List of elements",
"conditional": "Conditional test",
"word0": "Value0",
"word1": "Value1",
"word2": "Value2",
"word3": "Value3",
... |
def show_magicians(great_magicians):
for magician in great_magicians:
print(magician)
def make_great(magicians_names,great_magicians):
while magicians_names:
g_magician = magicians_names.pop()
g_magician = 'Great ' + g_magician
great_magicians.append(g_magician)
magicians_na... |
pet_0 = {
'kind' : 'dog',
'owner' : 'Juliana'
}
pet_1 = {
'kind' : 'cat',
'owner' : 'Ana'
}
pet_2 = {
'kind' : 'fish',
'owner' : 'Joao'
}
pets = [pet_0, pet_1, pet_2]
for p in pets:
print(p) |
message = input("Let me see whether I can find you a Subaru")
print(message) |
"""
Turtle Drawer
By Sean Ryan
"""
from TIGr import AbstractDrawer
import turtle
class TurtleDrawer(AbstractDrawer):
"""Turtle Drawer
Inherits:
select_pen(pen_num), pen_down(), pen_up(), go_along(along), go_down(down), draw_line(direction, distance)
Preset Pens:
1 - colour black, size 10
2... |
import math
import os
import random
import re
import sys
def countingSort(arr):
sorted_array = []
count_array = [0]*(len(arr))
for i in range(0, len(arr)):
count_array[arr[i]] += 1
for i in range(0, len(arr)):
if(count_array[i] != 0):
j = 0
while j < count_a... |
import math
import os
import random
import re
import sys
def repeatedString(s, n):
x = 0
total_a = 0
x = 0
for i in s:
if(i == 'a'):
total_a += 1
print(total_a)
return total_a
if __na... |
from turtle import Turtle
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.level = 1
self.color("black")
self.penup()
with open("highscore.txt") as data:
self.high_score = int(data.read())
self.hide... |
"""
Created on Thu Jun 28 23:02:21 2018
@author: hp
"""
numberList = [1,23,67,56,654,77,33,778,1,222,2345]
for eachNumber in numberList:
print(eachNumber)
for x in range(1,12):
print(x) |
valid_passwords = 0
with open("3.txt", "r") as f:
for line in f:
words = line.split()
positions = list(map(int, words[0].split('-')))
letter = words[1][0]
password = words [2]
if (password[positions[0]-1] == letter) != (password[positions[1]-1] == letter):
valid_passwords += 1
print(valid_passwords) |
class Time:
def __init__(self, h, m, s):
self.h = h
self.m = m
self.s = s
@property
def hours(self):
return self.h
@hours.setter
def hours(self, value):
if value >= 0 and value <= 23:
self.h = value
else:
raise ValueError("Inv... |
import sys
if len(sys.argv) < 2:
print("Usage : python table.py <number> [length]")
exit(1)
if len(sys.argv) == 2:
length = 10
else:
length = int(sys.argv[2])
num = int(sys.argv[1])
for i in range(1, length + 1):
print(f"{num:3} * {i:2} = {num * i:5}")
|
def output(string, outfile):
print(string)
outfile.write('%s\n' % string)
def floatToString(input_):
return ('%f' % input_).rstrip('0').rstrip('.')
def the_average_distance_of_each_data_point_from_the_mean_squared_then_square_rooted_to_remove_the_negative_sign_also_known_as_the_standard_d... |
def validateData(displayText, *args):
minimum = args[0] if len(args) >= 1 and isinstance(args[0], (float, int)) else float('-INF')
maximum = args[1] if len(args) >= 2 and isinstance(args[1], (float, int)) else float('INF')
while True:
try:
data = input(displayText)
... |
import power_of_a_number
import unittest
class Powbase(unittest.TestCase):
def test_is_natural_number_correctly_power(self):
self.assertEqual(power_of_a_number.returning_power_base_of_a_number(2, 2), 4)
def test_for_a_big_number(self):
self.assertEqual(power_of_a_number.returning_power_base_of... |
import sys
def reach(adj, x, y):
visited = {}
to_visit = [x]
while len(to_visit) > 0:
cur = to_visit.pop()
visited[cur] = True
if cur == y:
return 1
neighbors = adj[cur]
unvisited_neighbors = filter(lambda x: x not in visited, neighbors)
... |
class Persona:
def __init__(self, nombre, edad):
self.__nombre = nombre
self.__edad = edad
def __str__(self):
return "Nombre: "+self.__nombre+" y edad : "+str(self.__edad)
|
import tkinter as info
import tkinter as tk
class Application(info.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = info.Button(self)
self.hi_there[... |
print("Hello,world")
name = input("Enter your name: \n")
print("Hello, ", name) |
'''
/***************************************************************************************
Name : bearng
Description : calculates the bearing(angle) between given two lattitude and
longitude points
Parameters : l_lat1 and l_lng1 are point one lattitude and longitude respectively
... |
from aux import fermat_sum_of_squares as fss
def triplet(n):
'''Find 0 < a < b < c | a + b + c == n, a^2 + b^2 == c^2'''
qc = ((q, c) for c in xrange(n - 3, n / 3 - 1, -1)
for q in xrange(2 * n - 1, 2, -1)
if q + c == n)
valid... |
"""
The function input is an array as input.
The first element of the array is a string. The second is a number.
Make this function return the string repeated as many times as specified by the second element of the array.
If a negative number or zero is specified, return an empty string.
If any invalid parameters are... |
X = int(input(" A= "))
Y = int(input(" B= "))
even = 0
odd = 0
for number in range(X,Y + 1):
if(number % 2 == 0):
even = even + number
else:
odd = odd + number
print("The Sum of Even Numbers " ,even)
print("The Sum of Odd Numbers ",odd)
|
bis = int(input("enter number of biscuits "))
if bis == 3:
print("Not eaten")
elif 0 < bis < 3:
print("partly eaten")
elif bis == 0:
print("fully eaten")
else:
print("Enter 3 or any other number less than 3")
|
toppings = []
available_toppings = ('pomodoro', 'mozarella', 'funghi', 'salsiccia', 'alici', 'wurstel')
print(f"Questa e la lista delle possibili scelte per creare la tua pizza: {available_toppings}")
still_choosing = True
while still_choosing:
name = input("\n What ingredient do you want:")
toppings.append... |
beatles = []
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print("The beatles consist of ", beatles)
print("Both name must be enter as written below\n")
for i in beatles:
i = input("Enter the name \"Stu Sutcliffe\": ")
x = input("Enter the name \"Pete Best\... |
"""
Created on Sun Oct 14 17:58:25 2018
@author: Umaima
"""
def solution(N):
if N <=0 :
return 0
elif N == 1:
return 4
perimeter = []
i = 1
while i * i <=N:
if N % i == 0:
side1 = N / i
side2 = N / side1
perimeter.append(int(2... |
"""
Created on Mon Oct 15 16:59:07 2018
@author: Umaima
"""
def gcd(a, b):
mod = a % b
if mod == 0:
return b
else:
return gcd(b, mod)
def solution(N, M):
lcm = N * M /gcd(N, M)
res = lcm / M
return int(res)
N = 10
M = ... |
"""
Created on Fri Nov 2 15:58:51 2018
@author: Umaima
"""
def solution(S):
N = len(S)
if N == 0:
return 0
res = [0]
start = ""
end = ""
ecount = N-1
for i in range(0, N):
start = start + S[i]
end = S[ecount] + end
eco... |
"""
Created on Tue Oct 16 16:36:01 2018
@author: Umaima
"""
def solution(A):
N = len(A)
if(N < 3):
return 0
A.sort()
count = 0
for i in range(0, N):
z = i + 2
for j in range(i+1, N):
while z < N and (A[i] + A[j]) > A[z]:
... |
"""
Created on Mon Sep 23 14:00:30 2019
@author: huyn
"""
def constructSquare(s):
v = len(s)
ds = {}
dv = {}
for l in s:
if l not in ds:
ds[l]=0
ds[l]+=1
for key in ds:
val = ds[key]
if val not in dv:
dv[val]=[]
dv[val].append(k... |
"""
Problem
The Code Jam team has just purchased an orchard that is a two-dimensional matrix of cells of unprepared soil,
with 1000 rows and 1000 columns. We plan to use this orchard to grow a variety of trees — AVL,
binary, red-black, splay, and so on — so we need to prepare some of the cells by digging holes:
In o... |
"""
Created on Mon Sep 23 13:54:19 2019
@author: huyn
"""
def sort012Left(array):
zero = 0
one = 0
two = len(array)-1
while one <=two:
if array[one]==0:
array[zero],array[one] = array[one],array[zero]
zero+=1
one+=1
elif array[one]==1:
... |
"""
Created on Mon Sep 23 14:08:25 2019
@author: huyn
"""
def minEatingSpeed(piles, H):
def check(piles,K,H):
hour = 0
for p in piles:
hour+=p//K
if p%K:
hour+=1
return hour<=H
start,stop = 0, max(piles)
while start+1<stop:
... |
"""
Created on Sun Jul 14 15:00:25 2019
@author: huyn
"""
import heapq,typing
from collections import deque
class TreeNode(object):
def __init__(self, x,left=None,right=None):
self.val = x
self.left = left
self.right = right
def findCheapestPrice(n, flights, src, dst, k):
k+=1
... |
"""
Created on Sat Oct 5 23:03:33 2019
@author: huyn
"""
def countVowelPermutation(n: int) -> int:
d= {"a":"e","e":"ai","i":"aeou","o":"iu","u":"a"}
if n==1:
return 5
count = {"a":1,"e":1,"i":1,"o":1,"u":1}
for i in range(n-1):
newcount = {"a":0,"e":0,"i":0,"o":0,"u":0}
for l... |
"""
What are your chances of hitting a fly with a tennis racquet?
To start with, ignore the racquet's handle. Assume the racquet is a perfect ring,
of outer radius R and thickness t (so the inner radius of the ring is R−t).
The ring is covered with horizontal and vertical strings.
Each string is a cylinder of radi... |
"""
"""
import sys
T = int(input().strip())
def solve(instructions,R,C,SR,SC):
d = {"R":{},"C":{}}
d["R"][SC]=[[SR,SR]]
d["C"][SR] = [[SC,SC]]
visited = set()
visited.add((SR,SC))
for instruction in instructions:
if instruction=="N":
SR-=1
if (SR,SC) in visited:... |
import abc
class DataReader:
def __init__(self):
self.data = {}
def csvFile(self, path):
pass
def readFiles(self, path):
pass
class Indicator(metaclass=abc.ABCMeta):
"""Abstract class for an indicator.
Requires cols (of data) to be used for calculations"""... |
skills = {"Python", "Java", "Skateboarding", "Origami", "Woodworking"}
print(skills)
print("The number of skills in the set is", len(skills))
for skill in skills:
print(skill)
print()
if "origami" in skills:
print("Paper folding is my life.")
skills.add("Problem-Solving")
skills.update(["SQL", "Graphic ... |
file = open("Virginia_Census_2010.csv", "r", encoding="UTF-8-sig")
vmap = {}
for line in file:
line = line.rstrip("\n")
line = line.split(",")
city = line[0].strip()
population = int(line[1])
vmap[city] = population
print("The dictionary contains", len(vmap), "entries.")
print(vmap)
prin... |
size = 344
weight = 170
if size < 120:
if weight < 100:
print("It fits")
else:
print("Too heavy")
else:
print("Too big")
if size < 120 and weight < 100:
print("It fits")
else:
print("Too big or too heavy")
project_duration = 10
if project_duration > 30:
project_duration += 1... |
if __name__ == "__main__":
data = [ line.rstrip() for line in open("input", "r").readlines() ]
x = 1
y = 3
total = 0
width = len(data[0])
height = len(data)
while x < height:
total += int(data[x][y] == '#')
x += 1
y = (y + 3) % width
... |
"""
Created on Fri Mar 15 20:29:29 2019
@author: prakhar prakash
"""
list1 = list()
size = int(input('Enter the size of the list'))
for r in range(size):
list1.append(r)
list1[r] = int(input('Enter the value at location ' + str(r) + ':'))
print(list1)
def insertionsort(list1):
fo... |
"""
Created on Fri Mar 15 18:05:04 2019
@author: prakhar prakash
"""
list1 = list()
size = int(input('Enter the size of the list'))
for r in range(size):
list1.append(r)
list1[r] = int(input('Enter the value at location ' + str(r) + ':'))
print(list1)
def bubble(list1):
istrue = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.