text stringlengths 37 1.41M |
|---|
'''
Name: Terence Tong
Section: 202 - 9
'''
class StackArray:
"""Implements an efficient last-in first-out Abstract Data Type using a Python List"""
def __init__(self, capacity):
"""Creates and empty stack with a capacity"""
self.capacity = capacity # this is example for list implementation
... |
# Name: Terence Tong
# Class: CSC 202 - 9
# key things about the MaxHeap class,
# index[0] is empty,
# index[1] is the parent node,
# index[even] are left nodes
# index[odd] are right nodes
# ask about what the heap contents is supposed to return
class MaxHeap:
def __init__(self, capacity=50):
... |
"""
Name: Rohan Ramani, Terence Tong
Section: 202 - 9
"""
import random
# creates and prints a random list of numbers
def listGenerator():
alist = []
for i in range(100000):
# integer random numbers between 10 and 70
n = random.randint(10, 70)
alist.append(n)
print(alis... |
#This script runs a simple "Hang Man" game through the Windows command window
#This is a good starter assignment that includes looping, conditionals, simple built-in functions, and work with lists
#Author: Daniel Kuhman
#Contact: danielkuhman@gmail.com
#Date created: 1/27/2020
import random
import re
file_handle = op... |
# # program that asks the user to enter a list of integer
print("????????????????? Question1 ////////////////\n")
lis = []
n = int(input("Enter number of elements you want to save in list : "))
for id in range(n):
num = int(input("enter numbers: "))
lis.append(num)
# Print the total number of items in ... |
import unittest
from WordFrequency import pre_process, count_words, sort_words_by_count
class Test(unittest.TestCase):
def test_pre_process(self):
test_string = "This [is] a (sample) 100 @$string's, where we will test-string preprocessing ."
expected_output = "this is a sample string s where we wi... |
Min_equal_Max=[]
MinMax=[]
def find_max_min(fruits):
if (min(fruits))==(max(fruits)):
Min_equal_Max.append(len(fruits))
print(Min_equal_Max)
return Min_equal_Max
elif(min(fruits))<(max(fruits)):
MinMax.append(min(fruits))
MinMax.append(max(fruits))
... |
phone_number = {
"james": "945-394-2356",
"miranda": "648-384-2345"
}
result = phone_number["james"]
print ("This is James phone number",result)
result = phone_number["miranda"]
print ("This is Miranda's phone number",result) |
print("-----------задание 1---------")
print("Hello, World!")
print("Маша + Петя = Любовь")
x=3+4
print("x=3+4")
print("x=",x)
print("------------задание 2--------")
x='Hello, World!'
print(type(x))
x=3+4
print(type(x))
x=3/4
print(type(x))
x=[1,2,5,10,100]
print(type(x))
print("------------задание 3----... |
import random
import os
import time
clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')
# Score is going to be a global variable
user_score = 0
# Define few constant values
score_for_correct_guess = 10
score_for_wrong_guess = -3
range_dict = dict({'A': [1,10], 'B': [1,20], 'C': [1,50], '... |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date May 25 06:09:25 PM CST 2009
def foo(s):
m = 1
ms = s
for i in range(1, len(s)):
s = s[1:] + s[0]
#print 'ms=',ms, 's=', s
if s < ms:
ms = s
m = i+1
... |
import math
import numpy as np
def user_input() -> list:
'''
Пользовательский ввод для заполнения списка
'''
n = int(input("Введите n(размер массива): "))
arr = []
for i in range(0, n):
x = float(input("Введите число: "))
arr.append(x)
return arr
def o136(a):
"""
... |
from time import time
def print_board(arr, width=5):
"""Print a 2-demension array prettily
Args:
arr: the 2-demension array
"""
size = len(arr)
def g(x): return f'{x}'.rjust(width, ' ')
for i in range(size):
for j in range(size):
print(g(arr[i][j]), end='')
... |
# coding=utf-8
import tensorflow as tf
import numpy as np
# Placeholders are used to feed values from python to TensorFlow ops. We define
# two placeholders, one for input feature x, and one for output y.
x = tf.placeholder(dtype=tf.float32, shape=None, name='x')
y = tf.placeholder(dtype=tf.float32, shape=None, name... |
score = input("Enter Score: ")
fscore = float(score)
if fscore>1.0:
print('error')
elif fscore<0.0:
print('error')
elif fscore>=0.9:
print('A')
elif fscore>=0.8:
print('B')
elif fscore>=0.7:
print('C')
elif fscore>=0.6:
print('D')
elif fscore<0.6:
print('F')
|
f = open("input.txt", "r")
values = f.read().split()
passwords = values[2::3]
letters = [i[:-1] for i in values[1::3]]
mins_maxes = values[::3]
mins = [i[0:i.index("-")] for i in mins_maxes]
maxes = [i[i.index("-")+1:] for i in mins_maxes]
def pw_check(pw, letter, min, max):
count = 0
for char in pw:
if char ... |
def max_index(numbers):
return numbers.index(max(numbers))
def magician_and_chocolates_easy(box, taken_time):
chocolates = 0
while taken_time != 0:
large_box = max_index(box)
chocolates = chocolates + box[large_box]
if boxes[large_box] == 0:
break
box[large_box]... |
visited = []
ans = []
def dfs(graph, node, visited):
if node not in visited:
visited.append(node)
ans.append(node)
for neighbour in graph[node]:
dfs(graph, neighbour, visited)
return ans
if __name__ == "__main__":
graph = {
'A': ['B', 'C'],
'B': ['D', '... |
nome = input('Digite o seu nome: ')
idade = int(input('Digite o seu nome: '))
print('Seu nome é', nome)
print('Você tem', idade, 'anos')
|
from abc import ABC, abstractmethod
class Robot(ABC):
"""Abstract base class to control mobile robots."""
def __init__(self, client_id: int, track: float, wheel_radius: float):
"""Robot class initializer.
Args:
client_id: CoppeliaSim connection handle.
track: Distance... |
n = int(input("Please input a number:"))
test = (n % 2)
if test == 1:
print("odd number")
elif test == 0:
print("even number")
if n < 0:
print("negative number")
|
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
# crea un data set ficticio centrado alrededor de los 27000
# con distribucion normal y desviacion estandar de 15000 con 10000 data points
incomes = np.random.normal(27000, 15000, 10000)
print "Mean: ",np.mean(incomes... |
# 1 - Restrição entre diferença de Datas de Nascimento entre Pai e Filho
def dataNascimento_pai_filho(pai,filho):
if filho["nome"] in pai["ePai"]:
return int(filho["dataNasc"].split('-')[2]) > int(pai["dataNasc"].split('-')[2]) + 13
else:
return False
def dataNascimento_avo_m_filho(avo,pai,... |
from tkinter import *
global scvalue
def click(event):
text = event.widget.cget("text")
print(text)
if text == "=":
if scvalue.get().isdigit():
value = eval(screen.get())
else:
value = eval(screen.get())
scvalue.set(value)
screen.up... |
# Project Euler
# Problem 19: Counting Sundays
# You are given the following information, but you may prefer
# to do some research yourself.
# * 1 Jan 1900 was a Monday.
# * Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# ... |
# Project Euler
# Problem 18: Maximum Sum Path 1
# By starting at the top of the triangle below and moving to adjacent
# numbers on the row below, the maximum total from the top to bottom
# is 23.
# 3
# 7 4
# ... |
# Project Euler
# Problem 1: Multiples of 3 and 5
# Problem Details:
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get
# 3, 5, 6, and 9. The sum of these multiples is 23.
# Find the sum of all the multiples fof 3 and 5 below 1000.
#
# Jeffrey Spahn
# created for Python 3.x... |
# Project Euler
# Problem 2: Even Fibonacci Numbers
# Problem Details:
# Each new term in the Fibonacci sequence is generated by
# adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8 , 13, 21, 34, 55, 89
# By considering the terms in the Fibonacci sequen... |
# Project Euler
# Problem 26: Reciprocal cycles
# A unit fraction contains 1 in the numerator. The decimal representation
# of the unit fractions with denominators 2 to 10 are given:
#
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def generate(A, C, M, X0, N) -> int:
for _ in range(N):
X0 = (A * X0 + C) % M
return X0
def main() -> int:
n = int(input())
results = [''] * n
for i in range(n):
(... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = 'http://codeforces.com/problemset/problem/384/A'
__version__ = '1.0'
def print_chessboard(size: int) -> None:
n_coders = size * size // 2
line = ['C.' * (size // 2), '.C' * (size // 2)]
if size % 2 != 0:
n... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def main() -> int:
n = int(input())
exercises = [int(word) for word in input().split()]
total = [0] * 3
for i in range(3):
total[i] = sum(exercises[i::3])
max_index = total.... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__spec__ = 'http://codeforces.com/problemset/problem/282/A'
__version__ = '1.0'
n = int(input())
result = 0
for _ in range(n):
statement = input()
if ('++' in statement):
result += 1
elif ('--' in statement):
... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def find_point(n: int, k: int, squares: list) -> int:
if k > n:
return -1
squares = sorted(squares, reverse=True)
return squares[k - 1]
def main() -> int:
(n, k... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = 'http://codeforces.com/problemset/problem/379/A'
__version__ = '1.0'
def calculate_hour(candles: int, pieces: int) -> int:
hour = 0
went_outs = 0
while candles > 0:
hour += candles
went_outs += cand... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def sum_digit(string: str) -> int:
return sum(int(char) for char in string)
def is_lucky_ticket(n: int, ticket: str) -> bool:
if (ticket.count('4') + ticket.count('7')) != n:
... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def findab(x1: int, y1: int, x2: int, y2: int) -> tuple:
a = (y1 - y2) // (x1 - x2)
b = y1 - a * x1
return (a, b)
def main() -> int:
n = int(input())
results = [''] * n
for i ... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def count_stealing_ways(n: int, cookie_bags: list) -> int:
sum_cookies = sum(cookie_bags)
temp = sum_cookies % 2
return sum(1 for bag in cookie_bags if bag % 2 == temp)
def m... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__spec__ = ''
__version__ = '1.0'
print([x * x
for x in range(10)])
print([x * x
for x in range(10)
if x % 3 == 0])
print([(x, 2 * x)
for x in range(10)])
print([(x, y)
for x in range(3)
for y in... |
__copyright__ = ''
__author__ = 'Son-Huy TRAN'
__email__ = "sonhuytran@gmail.com"
__doc__ = ''
__version__ = '1.0'
def collatz(number: int) -> int:
count = 0
while number != 1:
number = number // 2 if number % 2 == 0 else number * 3 + 1
count += 1
return count
def main() -> int:
in... |
#!/usr/bin/python
import random
import tkinter as tk
from tkinter import messagebox
from PIL import ImageTk ,Image
import tkinter.font as font
from tkinter.simpledialog import askstring
def home():
game()
# Code to add widgets will go here...
window = tk.Tk()
window.rowconfigure([1,2,3,4,5,6,7,8],minsize=50)
... |
times = int(input())
result = []
for _ in range(times):
x = int(input())
if x % 7 == 0:
result.append(x * x)
for y in result:
print(y)
|
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
value=collections.Counter(s)
value1=collections.Counter(t)
if len(value)!=len(value1):
return False
else:
for i in value.keys():
if i ... |
"""A Queue with a capacity limit."""
CAPACITY = 3
class EmptyQueue(Exception):
"""Exception to throw for empty queue."""
class Queue:
def __init__(self):
self.capacity = CAPACITY
self.queue = []
def isEmpty(self):
if len(self.queue):
return False
else:
... |
"""
The item class and it's children
"""
class Item:
"""
Parent class for all items
"""
# All the important variables for a consumable item.
# The constructor that sets the.
# name, description, StackCap, Stack, and affect.
def __init__(self, name, desc, stack_cap, stack, drop_rate):
... |
# Describe the given number in terms of parity and being the prime number
def numberDesc():
nb = input('Podaj liczbe:')
if nb % 2 == 0:
print ("Liczba jest parzysta")
else:
if nb == 1:
print ("Liczba jest nieparzysta")
else:
check = 0;
for x in li... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import xlrd
import os
class read_Excel():
def read_excel(xls_name,sheet_name):
cls=[]
#获取excel路径
xlspath=os.path.join('D:\\',xls_name)
file=xlrd.open_workbook(xlspath)
sheet = file.sheet_by_name(sheet_name)#获取excel的sheet
... |
def romb(letter):
# not hardcoded
all_letters = 'abcdegfxyz'
# test cases assert
# check type
# check is alfa
find =all_letters.find(letter)
all_letters = all_letters[:find+1]
for char in all_letters:
distance = find - all_letters.find(char)
external = [' ' for _ in ran... |
# Copyright(c) 2011 Cuong Ngo
# Print the most character used in a sentence
list1 = []
spaces = " "
# Get the sentence
SENTENCE = input("sentence: ")
print(SENTENCE)
# Lowercase
sentence = SENTENCE.lower()
# Get rid of the space in a sentence
sentence = sentence.replace(" ", "")
# Convert sentence ... |
# Copyright (c) 2011 Cuong Ngo
# Guessing game
print("\tThink of a number between 1 and 10, but don't tell me what it is.\n")
print("\tThen hit enter.\n\n\n")
number = 5
answer = ""
while answer != "y":
answer = input("\nIs it " + str(number) + "? [y/n]")
if answer == "n":
answer = input("\nI... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 导入 MNIST 数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784]) # 输入的数据占位符:存放待识别的图片
y_actual = tf.placeholder(tf.float3... |
def maxProfit(prices):
lowest = float('inf')
profit = 0
prices.append(-float('inf'))
for i in range(0,len(prices)-1):
if prices[i] < lowest:
lowest = prices[i]
elif prices[i]>=prices[i-1] and prices[i] >= prices[i+1]:
profit += prices[i] - lowest
... |
from typing import TextIO, Any
f: TextIO
with open('third.txt', 'r', encoding='utf-8') as f:
zp: list[Any] = []
for line in f:
worker, salary = line.split()
zp.append(salary)
if 20000 > float(salary):
print(f'{worker}: зарплата меньше 20 000')
print(f'Средняя величина до... |
beg=int(input("enter the first number:"))
end=int(input("enter the last number :"))
print("the even numbers are ")
for n in range(beg,end+1):
if(n%2)==0:
print(n)
|
num=input("enter number:")
for i in range(0,5+1):
mul=num*i
print("the first five multiples of a number :",num,mul)
|
from util import advent_input
from collections import Counter, defaultdict
def valid(passphrase):
words = passphrase.split(' ')
c = Counter(words)
# check that the phrase has at most 1 of any word
return c.most_common(1)[0][1] == 1
def anagrams(words):
"""finds all sets of anagrams in wor... |
def spin_and_insert(nums, pos, to_insert, steps):
steps = steps % len(nums)
new_pos = (steps + pos) % len(nums)
nums.insert(new_pos + 1, to_insert)
return nums, new_pos + 1
def spin_state(current_pos, length, num_after_0, steps):
steps = steps % length
new_pos = (current_pos + steps)... |
n=int(input("enter a number"))
fact=1
i=1
for i in range(1,n+1):
fact=fact*i
i=i+1
print("factorial of",n,"is",fact)
|
n=int(input("enter a number"))
temp=n
reverse=0
while(n>0):
d=n%10
reverse=(reverse*10)+d
n=n//10
if(temp==reverse):
print("given number is palindrome")
|
n=int(input("enter a number"))
count=0
sum=0
while(n>0):
count=count+1
d=n%10
sum=sum+d
n=n//10
print("sum of number of digit of entered number is",sum)
print("the number of digit in the number are",count)
|
# The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
# открыть файл
file = open('madlibs.txt', 'r')
key_words = ['ADJECTIVE', 'NOUN', 'VERB']
words_found = []
file_obj = file.read()
file.close()
# сформировать список словарей ключевых слов с пустыми значениями
for word... |
import sys
from common import readArrayFromLine
def maxHeapify(arr, i, length):
left = (2 * i) + 1
right = (2 * i) + 2
largest = i
if left < length and arr[left] > arr[largest]:
largest = left
if right < length and arr[right] > arr[largest]:
largest = right
if largest != i:
... |
import sys
def func(a, b):
sum = 0
for num in range(a,b+1):
if num % 2 == 1:
sum += num
return sum
if __name__ == '__main__':
a = int(sys.argv[1])
b = int(sys.argv[2])
print func(a, b)
|
import sys
from common import readArrayFromLine
def binSearch(arr, val, start, end):
if start > end:
return -1
num = end - start
mid = start + (num / 2)
if arr[mid] == val:
return mid + 1
if num <= 1:
return -1
if arr[mid] < val:
return binSearch(arr, val, mid+1,... |
def code_generator(code1, code2):
code1_list= code1.split('-')
code2_list = code2.split('-')
code1_list = [int(item) for item in code1_list]
code2_list = [int(item) for item in code2_list]
while not code1_list == code2_list:
if code1_list[1] < 999:
code1_list[1] += 1
... |
def reverse(i):
y = i.split()
return" ".join(y[::-1])
i = (input("ENTER A SENTENCE\n"))
print(reverse(i))
|
def inventory_list(items_list, cmd):
cmd = cmd.split(' - ')
action = cmd[0]
item = cmd[1]
if action == 'Collect':
if item not in items_list:
items_list.append(item)
elif action == 'Drop':
if item in items_list:
items_list.remove(item)
elif action == 'Combi... |
num_str = input()
num_list = num_str.split()
inverted_list = []
for i in range(len(num_list)):
num_list[i] = int(num_list[i])
inverted_list.append(num_list[i] * -1)
print(inverted_list) |
def calculator(action, num1, num2):
if action == 'multiply':
return num1 * num2
elif action == 'divide':
return num1 // num2
elif action == 'add':
return num1 + num2
elif action == 'subtract':
return num1 - num2
operator = input()
number1 = int(input())
number2 = int(in... |
n = int(input())
word = input()
my_list = []
filtered_list = []
for _ in range(n):
sentence = input()
my_list.append(sentence)
if word in sentence:
filtered_list.append(sentence)
print(my_list)
print(filtered_list) |
line = input()
contests_dict = {}
individual_standings = {}
while line != 'no more time':
user_retake_same_contest = False
username = line.split(' -> ')[0]
contest = line.split(' -> ')[1]
points = int(line.split(' -> ')[2])
if contest not in contests_dict:
contests_dict[contest] = []
fo... |
def order_sum(item, amount):
if item == 'coffee':
sum = amount * 1.50
return sum
elif item == 'water':
sum = amount * 1
return sum
elif item == 'coke':
sum = amount * 1.40
return sum
elif item == 'snacks':
sum = amount * 2
return sum
orde... |
snowballs_number = int(input())
import sys
snowball_value_max = -sys.maxsize
for snowball in range(1, snowballs_number + 1):
snowball_snow = int(input())
snowball_time = int(input())
snowball_quality = int(input())
snowball_value = (snowball_snow / snowball_time) ** snowball_quality
if snowball_valu... |
old_favorite = input().split(' | ')
command = input()
new_favorite = []
while not command == 'Stop!':
if 'Join' in command:
action, genre = command.split()
if genre not in old_favorite:
old_favorite.append(genre)
elif 'Drop' in command:
action, genre = command.split()
... |
nums_list = [int(num) for num in input().split(', ')]
even_indexes_list = []
for num in nums_list:
if num % 2 == 0:
even_indexes_list.append(nums_list.index(num))
print(even_indexes_list)
|
n = int(input())
register_dict = {}
for _ in range(n):
command = input().split()
action = command[0]
name = command[1]
if action == 'register':
car_reg = command[2]
if name in register_dict:
print(f'ERROR: already registered with plate number {car_reg}')
else:
... |
def factorial_division(num_1, num_2):
num_1_fact = num_1
num_2_fact = num_2
for num in range(num_1 - 1, num_2, -1):
num_1_fact *= num
return f'{num_1_fact:.2f}'
n_1 = int(input())
n_2 = int(input())
print(factorial_division(n_1, n_2)) |
command = input()
chat = []
while command != 'end':
if 'Chat' in command:
action, message = command.split()
chat.insert(len(chat), message)
elif 'Delete' in command:
action, message = command.split()
if message in chat:
chat.remove(message)
elif 'Edit' in command:... |
mylist=[]
def mean(myList):
result_mean=sum(myList)/len(myList)
return result_mean
n=int(input("Enter the number of elements in the list"))
for i in range(n):
num=int(input("Enter list elements"))
mylist.append(num)
print("mean= ",mean(mylist))
|
import sys
def compute(filename):
f = open(filename,'r')
n = int(f.readline()[:-1])
for i in range(n):
temp = f.readline()[:-1].split(" ")
if int(temp[0])&1:
print "Case #"+str(i+1)+":",bottomTop(int(temp[1]))
else:
print "Case #"+str(i+1)+":",topBottom(int(te... |
def my_cube(y):
""" takes a value and returns the value cubed
uses the ** operator
"""
return(y ** 3)
print(my_cube(13))
|
# -*- coding: utf-8 -*-
"""
date: 07/26/17
author: stamaimer
source: https://leetcode.com/problems/merge-two-binary-trees/#/discuss
difficulty: easy
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
cl... |
"""
Date: 12/09/2020
Name: Rio Weil
Title: day10.py
Decription: 2020 AoC D10 - Count number of valid paths in a list of integers
"""
import numpy as np
## Functions:
def plusminusn_counter(loi, n):
# Counts the number of neighbouring elements that are n different in loi
# CONSTRAINT: loi must be sorted
co... |
def rearrange_digits(input_list=None):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if type(input_list) is not list or input_list is None or len(input_list) == 0:... |
"""
@package steg
A program for embedding character data into a greyscale image and extracting
data so embedded.
### Embedding text into an image
To embed a text file into the least-significant bits
of an 8-bit greyscale image execute the command
$ python steg.py embed in_img_file out_img_file data_file
wher... |
"""
@package duo_disp
A program for displaying two images side-by-side.
To run this program execute the following command:
python duo_disp.py
You can then select an image to display on either side by pressing the
"Choose" button. The image must be 8-bit greyscale.
Once an image is loaded, you can view a repres... |
def main():
num = eval(input("숫자를 입력하세요"))
if num % 2 == 0:
if num % 3 == 0:
print("2의 배수 이면서 3의 배수 입니다")
else:
print("NO")
else:
print("NO")
if num % 2 == 0 and num % 3 == 0:
print("2의 배수 이면서 3의 배수 입니다")
else:
pass
print("NO")
main()... |
class WordFilter(object):
def __init__(self, words):
"""
:type words: List[str]
"""
from collections import defaultdict
dict = defaultdict(list)
for i in range(0, len(words)):
tmpwords = words[i]
for j in range(0,len(tmpwords)+1):
... |
def longestPalindrome(s):
"""
:type s: str
:rtype: str
"""
n = len(s)
maxl = 0
start = 0
for i in range(0, n):
if i - maxl >= 1 and s[i - maxl - 1:i + 1] == s[i - maxl - 1: i + 1][::-1]:
start = i - maxl - 1
maxl += 2
continue
if i - ma... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in range(0, len(nums) - 1):
for j in range(i, len(nums)):
if nums[i] > nums[j]:
... |
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
if nums:
self.sumofnums = [0 for i in range(0, len(nums) + 1)]
self.sumofnums[0] = 0
for i in range(1, len(nums)+1):
self.sumofnums[i] = self.sumofnums... |
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
area = (C - A) * (D - B)... |
a=float(input("Enter 1st number: "))
b=float(input("Enter 2nd number: "))
if a%b==0:
print(a,"is divisible by",b)
else:
print(a,"is not divisible by",b)
|
a=float(input("Enter 1st multiple: "))
b=float(input("Enter 2nd multiple: "))
c=float(input("Enter 3rd multiple: "))
d=float(input("Enter 4th multiple: "))
e=float(input("Enter 5th multiple: "))
div=float(input("Enter value of divisor: "))
count=0
if a%div==0:
count+=1
if b%div==0:
count+=1
if c%div=... |
print("For Quadratic equation of general form ax^2+bx+c=0")
print("Enter values of a,b and c")
import math
a=float(input("Enter value of a: "))
b=float(input("Enter value of b: "))
c=float(input("Enter value of c: "))
d=b**2-4*a*c
x1=0
x2=0
if d>0:
x1=(-b+math.sqrt(d))/(2*a)
x2=(-b-math.sqrt(d))/(2*a... |
import numpy as np
class GamblersRuin(object):
"""
Three fair coins tossed. Heads gets +1, tails -1, pay-offs are added and net pay-off added to equity.
The 3 tosses are repeated 1000 times. Initial equity is 10 dollars
p: probability that gambler is successful/ wins at each round.
i: gambler's initial amount of ... |
import math
import operator
"""
create user similarity matrix
w[u][v] 对称矩阵
"""
def UserSimilarity(train):
# build inverse table for item_users
item_users = dict()
for u, items in train.items():# user - items
for i in items.keys():
item_users.setdefault(i, set())
... |
import matplotlib.pyplot as plt
import numpy as np
def transform(sample,j,operator):
'''
Transforms a given sample based on specified set of raising and
lowering operators. Transformed state can be used to obtain
corresponding amplitude coefficient in local estimator.
:param sample: Sample for wh... |
age=int(input("你的年龄:"))
if age >= 18:
print("你的年龄: %d 岁,你可以进网吧!" % age)
else:
print("未成年禁止入内!")
|
def print_line(char, times):
"""
打印出单行分隔线
:param char: 分隔字符
:param times: 每行分隔符个数
"""
print(char * times)
def print_lines(char, times, row):
"""
打印多行分隔线
:param char: 分隔符
:param times: 每行分隔符个数
:param row: 行数
"""
col = 0
while col < row:
print_line(char, t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.