text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
class Solution:
"""
@param matrix: a matrix of 0 an 1
@return: an integer
"""
def maxSquare2(self, matrix):
# write your code here
m = len(matrix)
n = len(matrix[0])
if m == 0 or n ==... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: A ListNode.
@return: A boolean.
"""
def isPalind... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 17:17:00 2019
@author: sensenliu
"""
class Solution:
"""
@param n: An integer
@return: A boolean which equals to true if the first player will win
"""
def firstWillWin(self, n):
coins = [False, True, True]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
height.append(0)
stack = []
ar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
DIR = [(0,1), (0,-1), (1,0), (-1,0)]
class Solution:
"""
@param board: A list of lists of character
@param word: A string
@return: A boolean
"""
def exist(self, board, word):
if not word:
return True
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 18:05:45 2019
@author: sensenliu
"""
class ListNode:
def __init__(self, val):
self.val = val ;
self.next = None
class MyQueue:
def __init__(self):
self.dummy = ListNode(-1)
self.tail = self.dummy
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
class Solution:
"""
@param: a: parameter of the equation
@param: b: parameter of the equation
@param: c: parameter of the equation
@return: a double array, contains at most two root
"""
def rootOfEquation(self, a, b, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
DIR = [(0,1), (1,0), (0, -1), (-1, 0)]
"""
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class UFS:
def __init__(self):
self.root_hash = {}
self.count = 0
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sensenliu
"""
"""
Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
"""
class Solution:
"""
@param {UndirectedGraphNode[]} nodes a array of undirected grap... |
'''
Câu hỏi:
Viết chương trình và in giá trị theo công thức cho trước: Q = √([(2 * C * D)/H]) (bằng chữ: Q bằng căn bậc hai của [(2 nhân C nhân D) chia H]. V
ới giá trị cố định của C là 50, H là 30. D là dãy giá trị tùy biến, được nhập vào từ giao diện người dùng, các giá trị của D được phân cách bằng dấu phẩy.
Ví dụ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import ast
############################################
#
# Get results from file that contains findings output
# in dictionary format. That is why we are using ast
# otherwise format will be as string when reading out of file.
#
def GetResults():
""" read findings fi... |
# _*_ coding:utf-8 _*_
# @time:2020/11/9 000921:18
# @Author:csw
# for i in range(1,10):
# for j in range(1,i+1):
# print("{}*{}={}".format(i,j,i*j),end=' ')
# print(' ')
for i in range(10):
for j in range(1,i+1):
print('{}*{}={}'.format(i,j,i*j),end=' ')
print(' ')
|
# _*_ coding:utf-8 _*_
# @time:2020/11/9 000923:42
# @Author:csw
####奇数之和
# a=0
# for i in range(10):
# if i %2==0:
# a+=i
# print(a)
# print(a)
import random
a=0
b=random.randint(0,100)
for i in range(b):
if i % 2 == 0:
a+=i
print(i)
print(a)
print(a) |
import random
number = random.randint(1, 2)
if number == 1:
print("Heads")
else:
print("Tails") |
import csv
from product import Product
FILENAME = "products.csv"
PRODUCT_FIELDNAMES = ("id", "name", "price")
def product_has_id(id, product_list):
for product in product_list:
if product.id == id:
return True
return False
def enlist_product(id, name, price, product_list):
if product_... |
name_list = ["Bob", "Eve", "John", "Joe"]
for i in range(0, len(name_list)):
print(name_list[i])
|
number = 10
guess = int(input("Guess a number: "))
if guess < number:
print("Your guess is too small")
elif guess > number:
print("Your guess is too large")
else:
print("You guessed the correct number!") |
s = input()
names = s.split()
for i in range(len(names)):
names[i] = names[i].capitalize()
print(" ".join(names))
|
cls = ['Shahzaib', 'Miraj', 'Jabbar']
for item in cls:
if item == 'Shahzaib':
print(item)
break
else:
print('The Student is not found') |
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def printArea(self):
return 0
class Rectangle(Shape):
type = "Rectangle"
sides = 4
def __init__(self):
self.length = 5
self.breadth = 4
def printArea(self):
return self.breadth * self.len... |
# Print First 10 natural numbers using while loop
# i = 0
# while i <= 10:
# print(i)
# i+=1
# Print the following pattern
print("Second Number Pattern ")
lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("") |
x = int(input("Enter first Number"))
print("press + for Addition")
print("press - for subtraction")
print("press * for Multiplication")
print("press / for Division")
a = input()
y = int(input("Enter second Number"))
if a=="+" or a=="-" or a=="*" or a=="-":
if a == "+":
if x == 56 and y == 9:
pri... |
class Employee:
no_of_leaves = 6
def __init__(self, aname, asal, arole):
self.name = aname
self.sal = asal
self.role = arole
def printdetails(self):
return f"My Name is {self.name} my Salary is {self.sal} and my role is {self.role}"
@classmethod
def changeleaves(cl... |
class Dad():
basketball = 2
class Son(Dad):
dance = 4
def isDance(self):
return f"Sunny Dance for {self.dance} no of times.."
class Grandson(Son):
dance = 9
score =100
def isDance(self):
return f"Grancy Dance for {self.dance} no of times " \
f"And Also scored {self.score} i... |
f1 = open("first.txt")
try:
f = open('does.txt')
except EOFError as e:
print('Printed! EOF Error: ', e)
except IOError as e:
print('Printed! IO Error: ', e)
else:
print('This will run only when Except in not running...')
# This is used for Code Clean up
finally:
print('Run this Anyway...')
f... |
import time
initial = time.time()
k = 0
while (k<10):
print("Loading...")
time.sleep(0.5)
time.perf_counter()
k+=1
print("While loop Ran in: ", time.time() - initial, "Seconds")
initial2 = time.time()
for i in range(10):
print("Loading...")
time.sleep(0.5)
print("For loop Ran in: ", time.time... |
class Employee:
no_of_leaves = 8
def __init__(self, aname, asal, arole):
self.name = aname
self.salr = asal
self.role = arole
def printDetails(self):
return f"My Name is {self.name} my salary is {self.salr} and my role is {self.role}"
@classmethod
def changeLeaves(... |
# read data file
f = open('d12-input.txt', 'r')
data = [line.rstrip() for line in f.readlines()]
#test data
# data = ["F10","N3","F7","R90","F11"]
# ensure input data in list
# data = [list(line) for line in data]
directions = {"E","S","W","N"}
rotations = {"L","R"}
current_posn = {"E":0, "S":0, "W":0, "N":0}
#dicti... |
import random
import hashlib
from datetime import datetime
import csv
# This function generates a random blood type
def rand_blood():
b = random.random()
if b < 0.45:
return 'O'
elif b < 0.85:
return 'A'
elif b < 0.95:
return 'B'
else:
return 'AB'
# This function ... |
#inversão é tu achar uma tupla dada por uma comparação - (x,y) tal que x>y
#quando o merge joga o elemento da partição da direita para a esquerda
#é porque ele achou um x>y então para todo elemento que resta na partição da esquerda x<=y
#básicamente nós contamos todas as inversões feitas em todas as partições, pois se... |
halves = [(idx / 2) for idx in range(1, 100)]
print(halves)
fizz = [num for num in range(1, 100) if num % 3 == 0]
print(fizz)
rows = range(4)
cols = range(10)
print([(x, y) for x in rows for y in cols])
total_nums = range(1, 101)
fizz_buzzes = {
'fizz': [n for n in total_nums if n % 3 == 0],
'buzz': [n for... |
# https://leetcode.com/problems/sort-colors/
# 75. Sort Colors
# Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2 to represent the color red, whit... |
# https://leetcode.com/problems/subarray-sums-divisible-by-k/
# 974. Subarray Sums Divisible by K
# Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
# Example 1:
# Input: A = [4,5,0,-2,-3,1], K = 5
# Output: 7
# Explanation: There are 7 subarrays... |
# https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/
# 1481. Least Number of Unique Integers after K Removals
# Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
# Example 1:
# Input: arr = [5,5,4], k = 1
# Ou... |
# https://leetcode.com/problems/linked-list-in-binary-tree/
# 1367. Linked List in Binary Tree
# Given a binary tree root and a linked list with head as the first node.
# Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise... |
# https://leetcode.com/problems/delete-nodes-and-return-forest/
# 1110. Delete Nodes And Return Forest
# Given the root of a binary tree, each node in the tree has a distinct value.
# After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
# Return the roots of the... |
# https://leetcode.com/problems/combination-sum-ii/
# 40. Combination Sum II
# Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
# Each number in candidates may only be used once in the combination... |
# https://leetcode.com/problems/unique-binary-search-trees-ii/
# 95. Unique Binary Search Trees II
# Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
# Example:
# Input: 3
# Output:
# [
# [1,null,3,2],
# [3,2,null,1],
# [3,1,null,null,2],
# [2... |
# https://leetcode.com/problems/island-perimeter/
# 463. Island Perimeter
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
# Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exa... |
# https://leetcode.com/problems/unique-binary-search-trees/
# 96. Unique Binary Search Trees
# Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
# Example:
# Input: 3
# Output: 5
# Explanation:
# Given n = 3, there are a total of 5 unique BST's:
# 1 3 ... |
# https://leetcode.com/problems/longest-palindromic-substring/
# 5. Longest Palindromic Substring
# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
# Example 1:
# Input: "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# Example... |
# https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
# 1296. Divide Array in Sets of K Consecutive Numbers
# Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers
# Return True if its possible otherwise... |
# https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/
# 632. Smallest Range Covering Elements from K Lists
# You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.
# We define the range [a,b] is smaller than... |
# https://leetcode.com/problems/making-file-names-unique/
# 1487. Making File Names Unique
# Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].
# Since two files cannot have the same name, if you en... |
# https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/
# 1333. Filter Restaurants by Vegan-Friendly, Price and Distance
# Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.
... |
#Calculate Grade
def CalculateGrade(result_of_score):
if result_of_score >= 90:
result_of_grade = "A"
elif(result_of_score >= 75):
result_of_grade = "B"
elif(result_of_score >= 60):
result_of_grade = "C"
elif(result_of_score >= 50):
result_of_grade = "D"
else:
... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getTimes' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER_ARRAY time
# 2. INTEGER_ARRAY direction
#
from collections import deque
def getTime... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'protectionTime' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY startingPos
# 2. INTEGER_ARRAY speed
#
import sys
INF = sys.maxsize
ret = 0
d... |
#password.py
#조건은 다음과 같음
#1. 최소한 10글자 이상
#2. 최소한 1글자의 대문자
#3. 최소한 숫자 하나
#4. 최소한 다음 특수문자 중 하나 사용($#%&*)
#5. 공백없이
def CheckLength(string_password):
if len(string_password) < 10:
return False
return True
def CheckUpper(string_password):
for word in string_password:
if word.isupper():
... |
#DAY07_24DEC2016_Code009.py
#NOTES
'''
Anagrams
--> from collections import Counter
It return a dictionary with key and count as it's values
'''
#QUES
'''
Check for anagrams
'''
#SOLUTION
def anagram(str1,str2):
from collections import Counter
if(Counter(str1) == Counter(str2)):
return True
else:
retur... |
#DAY07_24DEC2016_Code010.py
#NOTES
'''
List functions
1. insert()
2. remove()
3. print()
4. sort()
5. pop()
6.remove()
'''
#QUES
'''
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of intege... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
def categorical_clean(col, numeric, dummies):
col_clean = pd.DataFrame(col)
col_name = col_clean.columns[0]
if numeric == True:
labelencoder = LabelEncoder()
col_clean.ix[:,col_name] = labelencod... |
initial_investment = int(input("Initial Investment: "))
apy = float(input("APY: "))
time_of_investment = int(input("Time invested(in years): "))
years = 0
investment_total = initial_investment
while years < time_of_investment:
investment_total = investment_total + (investment_total * (apy / 100))
years += 1
pr... |
"""
Reddit Daily Programmer
Easy Challenge 249
https://www.reddit.com/r/dailyprogrammer/comments/40h9pd/20160111_challenge_249_easy_playing_the_stock/
Hector Ramos
1/15/2016
"""
def maxProfit(inputList):
inputList = inputList.split(" ")
listLength = len(inputList)
for i in xrange(listLength):
in... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tuesday Oct 2, 2018
@author: Madhuri Suthar, PhD Candidate in Electrical and Computer Engineering, UCLA
"""
# Imports
import numpy as np
# Each row is a training example, each column is a feature [X1, X2, X3]
X=np.array(([0.2,-1,10,0.78],[15,-1,8,1... |
def personal_details():
name = input("Enter name of a person:")
age = int(input("Enter the age of a person:"))
gender = input("Enter the gender of a person:")
salary = int(input("Enter the salary of a person:"))
state = input("Enter the residing state of a person ")
city = input("Enter the... |
# https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/
from typing import List
def minOperations(grid: List[List[int]], x: int) -> int:
nums=list([]) # convert into vector
for i in range(len(grid)):
nums.extend(grid[i])
n=len(nums)
if n==1: return 0
nums.sort() # ... |
from collections import deque
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# DLR
def preorderTraversal(root: Optional[TreeNode]):
if root:
print(root.val)
preorderTravers... |
class HorseTour:
def __init__(self):
self.board=[[0 for i in range(8)] for j in range(8)] # 8x8 board
self.done=False
# NOTE: not a full cycle
def move(self, x:int, y:int, n:int):
if not self.done and 0<=x<8 and 0<=y<8 and self.board[x][y]==0:
self.board[x][y]=n # mark ... |
"""
Data Loaf usage example: Ghiscari names
Builds names that sound like Ghiscari characters from George R. R. Martin's
"A Song of Ice and Fire" novels.
"""
from __future__ import print_function
import dataloaf as loaf
start = loaf.choice('Gr Kr Pr Ozn Gh H N'.split())
vowel = loaf.choice('e a ah i y o'.split())
middl... |
#!/usr/bin/env python
from string import maketrans
def reverse_complement_dna(dna):
transtab = maketrans('ATCG', 'TAGC')
return dna.translate(transtab)[::-1]
def main():
with open('data/rosalind_revc.txt') as input_data:
dna = input_data.read().strip()
rev_comp = reverse_complement_dna(dna)
print rev_comp... |
#covid tracker
for i in range(1,100):
print(" ")
#importing covid module
from covid import Covid
print("Covid Tracker")
cv=Covid()
#global results with the help of predefined functions
#assigned variables to the predefined functions
act=cv.get_total_activ... |
#!/usr/bin/python3.5
# example.py
#
# CSCI 403 example Python script
#
# Author: C. Painter-Wakefield
# Modified: 10/31/2015
#
# This script does a couple of SELECT queries against tables in public, then
# creates a table and attempts some modification queries on it. Examples are
# given of prepared queries using par... |
# 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 flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-... |
import random
import os
import time
while True:
words = ["hangman", "chairs", "backpack", "bodywash", "clothing", "computer", "python", "program", "glasses", "sweatshirt",
"sweatpants", "mattress", "friends", "clocks", "biology", "algebra", "suitcase", "knives", "ninjas", "shampoo"
]
myString = random... |
print("Olá, vamos calcular sua média!")
print("\nVamos começar com as suas Atividades Contínuas.")
print("\nUtilizaremos suas quatro melhores notas...")
ac_1 = float(input("\nQual foi sua nota na primeira AC ? \n> AC 1: "))
ac_2 = float(input("Qual foi sua nota na segunda AC ? \n> AC 2: "))
ac_3 = float(input("Qual fo... |
import math
print("Olá, vamos calcular a o dobro da área de um quadrado!")
side = float(input("> Qual o lado do quadrado que vamos calcular? \n> Lado: "))
area = math.pow(side, 2)
print("\n> O dobro da área é", area * 2) |
# Problem 1 - Leap year
# A leap year is a year that experiences the addition of one day with the aim of adjusting the date to the astronomical year. In one year not exactly consists of 365 days, but 365 days 5 hours 48 minutes 45.1814 seconds. If this is ignored, then every four years will be deficient almost 1 day. ... |
import random
separador = "\n"*15 #15 saltos de linea para mejorar la meta-interfaz
finDeJuego = False #Esta variable se encarga de parar el bucle del programa principal
INDICEDEBOMBAS = 6.3 #Tablero original = 18x14 - 40bombas 18*14/40=6.3
coordenadas=[] #Se declara la lista vacia para meter las coordenadas
def pedi... |
'''Introductions into using "Pandas": Simple work with two distributions
Pandas is a Python framework for statistical analysis. It allows you to label
and group data, etc.
'''
'''
Author : Thomas Haslwanter
Date : March 2013
Ver : 1.1
'''
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as pl... |
#!/bin/python3
import math
import os
import random
import re
import sys
# write your code here
def avg(*arr):
if len(arr)==0:
return 0
total=0
for num in arr:
total=total+num
return total/len(arr)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nu... |
import re
def next_line_start(text, pos):
next_eol = text.find("\n", pos)
if next_eol < 0:
return len(text)
return next_eol+1
def start_of_line(text, pos):
if pos >= len(text):
return len(text)
while pos > 0:
if text[pos-1] == "\n":
return pos
pos -= 1
return 0
def next_line_start_or_here(text, pos)... |
#!/usr/bin/env python
'''
Homework2.py -- HW2 for EE 596, skin pixel finding algorithm using K means and classifiers
Created on Oct 16, 2015
@author: Keith Mikoleit
'''
def OpenImage(filepath, RG):
import cv2
import numpy as np
"""
Opens a color image. If RG is true, the image pixels are converted to ... |
import pygame
class Bird:
"""Holds data about the player bird"""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
# Sets up the PyGame internals
pygame.init()
# Size of the window
screen_width = 288
screen_height = 512
# How high up the screen the ground extends
ground_height = int(sc... |
# Arithmetic Operations
#======================
#----------------------
try:
x= float(input("Enter X : "))
y= float(input("Enter Y : "))
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x%y)
print(x**y)
except Exception as ex1:
print('Error:',ex1) |
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
#
# 示例 1:
# 输入: 123
# 输出: 321
#
# 示例 2:
# 输入: -123
# 输出: -321
#
# 示例 3:
# 输入: 120
# 输出: 21
# 注意:
#
# 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
class Solution:
def reverse(self, x: int) -> int:
result_list = []
if x < 0:
... |
#------------------------------------------------------------------
# Kenji Miyajima
# OCNG689
# 2013-12-04
#---------------------------------------------------------------------
# Functions draw a simple default mtplotlib scatter graph, an improved
# version of it by reading color data from ColorBrewer website and
# c... |
global assigned_value
global sat
global clause
global var_assignment
global final_assignment
global var_count
global clause_count
global li_list
global li_count_list
global li_priority_list
global lit_assigned
def solve(clause_no):
global final_assignment
global var_assignment
global sat
... |
"""Parameters, Unpacking, Variables."""
from sys import argv
# Run scripts with 4 variables.
script, first, second, third, last = argv
last_last = raw_input("Your one more variable is:")
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your... |
# Name: Moustafa Eid
# Date: May 8 2017
# Class: ICS3U1-03
# Description: Summative - E-Hoops
# Importing all necessary sources
import pygame
import random
import math
# Initiating pygame and Creating screen
pygame.init()
size = (width, height) = (800, 600)
screen = pygame.display.set_mode(size)
# Define colours
RED... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 30 09:49:30 2019
@author: sandip bandyopadhyay
"""
# =============================================================================
# def single_letter_count(word, leter):
# word = word.lower()
# leter = leter.lower()
# number = word.coun... |
class MapCell():
def __init__(self,name,parent):
self.name = name
self.parent = parent
self.id = parent.GetCellID()
self.neighbors = []
self.left = ""
self.right = ""
self.up = ""
self.down = ""
def SetNeighbor(self,side,cell):
if side... |
"""rock beats scissor
scissor beats paper
paper beats rock"""
player1 = input("Enter the Player one name: ")
player2 = input("Enter the Player two name: ")
player1_ans = input("Enter the player one answer: ")
player2_ans = input("Enter the player two answer: ")
if(player1_ans==player2_ans):
print("G... |
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
name1_lower = name1.lower()
name2_lower = name2.lower()
count_t = name1_lower.count("t") +... |
class LazyOperation():
""" Isolate the function call from the function execution.
out = LazyOperation(function,*args,**kwargs) defines the operation.
out.eval() evaluates the operation.
out.eval() = function(*args,**kwargs).
"""
def __init__(self,function,*args,**kwargs):
self._f =... |
import json
import os
# import tkinter from python libs
# you neee python 3.9.2,to run...
from tkinter import *
from tkinter import messagebox
# filenameYouwannaOpen
# variable will create or open a file with the name you specified...
fileNameYouwannaOpen = "content.json";
class loadJsonFileToProgram:
def __i... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
def puntouno(i,j,k):
z[i][j]=k
if i==n and j==n:
return z;
#el que baja un (i,0)
elif ((((i+j)%2==0 and i==j) or ((i+j)%2!=0 and i==j+1)) and (i+j<n-1)):
puntouno(i+j+1,0,k+1)
#el que baja un (nf-1,i+j+1-n)
elif... |
def main():
sumOfAll = 0
for num in range(5):
num = float(input('Please enter a number that includes a decimal. '))
sumOfAll = sumOfAll + num
print('The sum of all the numbers you entered is', sumOfAll)
main()
|
class lessFoodException(Exception):
def __init__(self,food_quantity):
message = "Food given was"+str(food_quantity)+"kg. Please increase food quantity"
super().__init__(message)
class moreFoodException(Exception):
def __init__(self,food_quantity):
message = "Food given was"+str(food_qua... |
class juggler:
def __init__(self,name):
self.__name=name
def juggles(self,juggling_item):
print(self.__name+"performs juggling using: "+juggling_item.get_name())
class jugglingItem:
def __init__(self,name):
self.__name=name
def get_name(self):
return self.__name
|
# Library Management System using Abstraction and Encapsulation
class Library:
def __init__(self):
self.Books = ['Cengage-Physics', 'IE Irodov', 'N Avasthi', 'RD Sharma', 'HC Verma', 'JD Lee']
def ShowBooks(self):
self.num = len(self.Books)
print("We have", self.num, "boo... |
import numpy as np
def LTV_basic(df, filter_list):
"""This function calculates lifetime value in a basic way.
Here, we simply sum the total transaction amount divided by the total
unique customers. We use this across a ten year period to describe our
basic lifetime value.
Pass in the dat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
"""
print("hola mundo " + str(os.getpid()))
os.fork()
print("esto esta despues del fork "+ str(os.getpid()))
os.fork()
print("segundo fork "+ str(os.getpid()))
#hay una incosistencia de la cantidad de prints que hace(a veces 6 otras 7)
"""
for i in ... |
#!/usr/bin/python
# example code using the nacl library is from:
# https://pynacl.readthedocs.io/en/latest/public/#example
#
# see also: https://github.com/pyca/pynacl/issues/150
import binascii
import nacl.utils
import nacl.secret
import nacl.utils
from nacl.public import PrivateKey, Box
# this code has Bob se... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""Accepted but slow-ish. still technically has O(n) time complexity and O(1) storage"""
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
# get the length of t... |
def doThing():
for i in range(0,9):
for j in range(0,9):
print("i: " + str(i) + " -> " + str(3*(i%3) + j//3) + " j: " + str(j) + " -> " + str(j%3 + 3*(i//3))) |
# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
nums = []
... |
from memoized import memoized
def base_p_expansion(n, p, padlength = 0):
"""Return the base p expansion of n as a list [d_0, d_1, d_2, ...] so that sum(d_i p^i) = n"""
result = []
while n != 0:
result.append(n % p)
n //= p
while len(result) < padlength:
result.append(0)... |
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 = {}... |
import random
import time
print("Welcome to the Magic 8 Ball!")
question = input("What is your question? ")
while question[len(question)-1] != '?':
print()
print("A question must contain a question mark at the end")
print("Please ask again with a question mark")
print()
question = input("What is you... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.