text stringlengths 5 121k |
|---|
def sum_dec(func):
def inner(a,b):
return a+b
return inner
def sub_dec(func):
def inner(a,b):
c=a+b
c1=c*2
return c1
return inner
@sub_dec
@sum_dec
def add(a,b):
print('the values of sum:',a+b)
add(2,4)
def wish_dec(func):
def inner(name):
... |
class supermarket:
def __init__(self,cnumber,item,cost,qty):
self.cnumber=cnumber
self.item=item
self.cost=cost
self.qty=qty
def total(self):
print('*'*30)
print('cnumber items cost qty')
print('*'*30)
print('number is:',self.cnumber)
pri... |
class student:
def __init__(self,sno,sname):
self.sno=sno
self.sname=sname
def sinfo(self):
print("the student number is:",self.sno)
print("the student name is:", self.sname)
s1=student('08DN1A0526', 'irfankhan')
s1.sinfo() |
rows = input()
cols = int(rows) * 3
for i in range(int(rows)//2):
print((".|."*(2*i+1)).center(int(cols),"-"))
print("WELCOME".center(int(cols),"-"))
for i in reversed(range(int(rows)//2)):
print((".|."*(2*i+1)).center(int(cols),"-"))
|
def fun(x):
return (2*x+1)**0.5
def dfun(x):
return 1/(2*x+1)**0.5
def dy(x, y):
return y - 2*x/y
xn = 0
yn = fun(xn)
h = 0.1
xn1 = xn + h
yn1 = yn + h * dy(xn, yn)
print('yn+1\'', yn1)
for i in range(20):
yn1 = yn + h * dy(xn1, yn1)
print('yn+1', yn1)
print('y(xn+1)', fun(xn1)) |
import speech_recognition as sr
from time import ctime
import time
import os
import sys
from gtts import gTTS
def speak(audioString):
print(audioString)
tts = gTTS(text=audioString, lang='en')
def recordAudio():
r = sr.Recognizer()
with sr.Microphone() as source:
p... |
diccionario = {
'nombre':'Carlos',
'edad':'22',
'cursos':['Python','Flask']
}
print(diccionario)
print(diccionario['nombre'])
print(diccionario['edad'])
print(diccionario['cursos'])
print(diccionario['cursos'][0])
print(diccionario['cursos'][1])
dic = dict(nombre='Juan',apellido='Juarez',edad=22)
print(dic['nombre'])
... |
def kidsWithCandies(candies, extraCandies):
sol = []
for c in candies:
if c+extraCandies>=max(candies):
sol.append(True)
else:
sol.append(False)
return sol |
import math
def Servo_angle_calcul(vanishingpoint):
height = 360 - vanishingpoint[1]
width = vanishingpoint[0] - 240
angle = 180*(width/height) / math.pi
print(angle)
if angle > 30:
return 1
elif angle < -30:
return -1
else:
return angle/30
|
import sys
def marsExploration(s):
length=len(s)
multiple=len(s)//3
p=0
q=3
count=0
for i in range(multiple):
new_sub_string=s[p:q]
if new_sub_string[0]!='S':
count+=1
if new_sub_string[1]!='O':
count+=1
if new_sub_string[2]!='S'... |
import pyttsx3
import datetime
import speech_recognition as sr
import webbrowser
import wikipedia as wiki
import tkinter as tk
engine =pyttsx3.init('sapi5')
voices= engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def myWindow()... |
class Account:
'Class to hold accounts'
def __init__(self, acc):
'Initializer for Account class'
self.accountNumber = acc
self.transactionList = []
self.balance = 0.0
def __str__(self):
'String representation for an instance of Account'
return '{0:<20} {1:<20} \n{2:<20} ${3:<20.2f}'.format("... |
def print_reversed_list_integer(my_list=[]):
if not my_list:
pass
else:
for list_reverse in reversed(my_list):
str = "{:d}"
print(str.format(list_reverse))
|
def inherits_from(obj, a_class):
"""
function that verifies if is an instance of a class
that inherited (directly or indirectly)
Return True if is an instance of a class
Return False otherwise
"""
if isinstance(obj, a_class) and type(obj) is a_class:
return(False)
else:
... |
import binascii
for alp in range(97, 123):
print(end="{:c}".format(alp))
|
point = int(input("Enter you score : "))
grade = ["A", "B+", "B", "C+", "C", "D+", "D", "F"]
score = [80, 75, 70, 65, 60, 55, 50, 0]
z = 0
for y in grade:
if point >= score[z]:
print("Grade : " + grade[z])
break
z = z + 1
|
"""Using this network setup, I have achieved a maximum accuracy
of 98.06% on the MNIST dataset."""
import numpy as np
import network_library
import mnist_loader
data = mnist_loader.load_mnist()
training_data = data[0]
training_labels = data[1]
validation_data = data[2]
validation_labels = data[3]
test... |
import os.path
import sys
def Isfile(file):
if os.path.isfile(file):
return 1
else:
return -1
def Find(file, text):
isfile = Isfile(file)
if isfile == -1:
return -1
load = open(file, "rb")
_read_ = load.read()
load.close()
decoding = _read_.decode(encoding = "... |
import copy, math, cmath
def Newton(f, dfdx, x, eps):
f_value = f(x)
it = 0
while True:
prev_x = x
x = x - float(f_value)/dfdx(x)
f_value = f(x)
it += 1
if abs(x - prev_x) < eps:
return x, it
def f(x):
return x**3 + x**2 - x - 0.5
def dfdx(x):
return 3*x**2 + 2*x - 1
... |
"""Assignment 02 - 09 Jacob B,"""
class phoneNumber:
DEFAULT_NUMBER = "0000000000"
def __init__(self, phone_num=DEFAULT_NUMBER):
self._phone_num = phone_num
try:
self.phone_number = self._phone_num
except TypeError:
self._phone_num = sel... |
from Phone_Number import phoneNumber
phone_num1 = phoneNumber("***650--688--0850***#")
print(f"Phone number for phone_num1 is {phone_num1}")
phone_num2 = phoneNumber("***650--688--0850**#")
print(f"Phone number for phone_num1 is {phone_num2}")
""""
Phone number for phone_num1 is (000) 000-0000
Phone number for phone... |
from typing import Dict, List, Set
f: Dict[str, str]
f = {
'a': 'b'
}
g: List[int]
g = [1,2,3]
h: Set[int]
h= set()
print(f,g,h) |
class Solution:
def sortList(self, head):
if head == None or head.next == None:
return head
fast = head
slow = head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
... |
def YUVfromRGB(R, G, B):
Y = 0.257 * R + 0.504 * G + 0.098 * B + 16
U = -0.148 * R - 0.291 * G + 0.439 * B + 128
V = 0.439 * R - 0.368 * G - 0.071 * B + 128
return Y,U,V
def RGBfromYUV(Y, U, V):
Y -=16
U-=128
V -=128
R = 1.164 * Y + 1.596 * V
G = 1.164 * Y - 0.392 * U - 0.813 * V
B = 1.164 * Y + ... |
class Person(object):
def __init__(self,name):
self.name=name
def getName(self):
return self.name
def isEmployee(self):
return False
p1= Person("Harry")
print(p1.getName())
print(p1.isEmployee())
print("================")
class ChildClass(Person):
def isEmployee(self):
... |
"""DICTIONARY"""
dictionary={'key1' : 'india','key2' : 'USA'}
print(dictionary['key1'])
print("===================")
dictionary={'key1' : 'india','key2' : 'USA'}
dictionary['key3']='Pakistan'
print(dictionary)
print("===================")
dictionary={'key1' : 'india','key2' : 'USA','key3':'Pakistan'}
dictiona... |
a=10
if(a<0):
print("a is a negative number")
elif(a>0):
print("a is a postive number")
else:
print("a is a zero")
print("number is : "+str(a))
|
def build_dictionary(keys, values):
dic = {}
for i in range(len(keys)):
dic[keys[i]] = values[i]
return dic
def merge(dic1, dic2):
for key, value in dic1.items():
if key not in dic2:
dic2[key] = value
else:
dic2[key] = dic1[key] + dic... |
number = int(input('enter a number:'))
n = 1
counter = 0
while n <= number:
if number % n == 0:
counter += 1
n += 1
if counter > 2:
print('not prime number')
else:
print('prime number') |
a = int(input("enter a value for a: "))
if a > 0:
print("a is positive")
if a % 2 == 0:
print("a is even")
else:
print("a is odd")
else:
print("a is negative") |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
return 'hi'
p1 = Person('jerry', 10)
p2 = Person('tom', 20)
print(p1.name)
print(p1.age)
print(p2.name)
print(p2.age)
p1.say_hi()
p2.say_hi()
class S... |
list = [3, 8, 9, 5]
res = [True if i % 3 == 0 else False for i in list]
list = ['apple', 'orange', 'pear']
res = []
for i in list:
res.append(i[0].upper())
res = [i[0].upper() for i in list]
[(i, len(i)) for i in list] |
l = [3, 2, 1, 4, 5, 6]
target = 6
sorted(l)
left = 0
right = len(l) - 1
while left < right:
tmp = l[left] + l[right]
if tmp == target:
print(l[left], l[right])
elif tmp < target:
left += 1
elif tmp > target:
right -= 1
... |
def factorial(n):
result = 1
while n > 0:
result = result * n
n -= 1
return result
print(factorial(5))
print(factorial(3)) |
s = 'abcd'
|
d = {}
for i in range(11):
d[i] = 10 - i
print(d)
|
def contain(list1, list2):
list2_contains_list1 = True
for i in list1:
if i not in list2:
list2_contains_list1 = False
list1_contains_list2 = True
for i in list2:
if i not in list1:
list1_contains_list2 = False
return list1_contains_list2 or... |
class MyClass:
num = 12345
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return "hello"
a = MyClass("Tom", 1)
print(a.name)
|
b = 1, 2, 3
print(type(b))
x, y = b
print(x)
print(y)
|
'''
Write a function that takes an ordered list of numbers
(a list where the elements are in order from smallest to largest)
and another number. The function decides whether or not the
given number is inside the list and returns (then prints) an appropriate boolean.
'''
def element_search(ordered_list, number):
if ... |
from datetime import datetime
year=datetime.now().year
name = input("Enter Your Name: ")
print(f"Hello Mr.{name}")
age = int(input("How old are you: "))
new_data = str((year-age)+100)
print(f"{name} you will be 100 years old in the year {new_data}")
|
'''
A
B C
D
'''
'''
MRO (method resolution order) rule tells that if a method is not available in class d,
then it verifies the method in class B, if not available
then it checks in class C.
in this case, class B method is executed..
'''
class A:
def method(self):
print("This is method from... |
from zipfile import ZipFile, ZIP_STORED
f = ZipFile('files7.zip', 'r', ZIP_STORED)
names = f.namelist()
print(names)
print('')
for name in names:
print('FileName: ',name)
print('The content of this file: ')
f1 = open(name, 'r')
print(f1.read())
print('*'*10)
|
'''
Write a program (function!) that takes a list and returns a new
list that contains all the elements of the first list minus all the duplicates.
Extras:
Write two different functions to do this - one using a loop and constructing a
list, and another using sets.
Go back and do Exercise 5 using sets, and write the so... |
from collections import OrderedDict
d = OrderedDict()
for _ in range(int(input())):
item, space , quantity = input().rpartition(' ')
if item not in d:
d[item] = int(quantity)
else:
d[item] += int(quantity)
for i, q in d.items():
print(i, q)
|
import re
email="zuck26@facebook.com" "page33@google.com" "jeff42@amazon.com"
output=re.findall("(\w+)@([A-Z0-9]+)\.([A-Z]{2,3})",email,flags=re.IGNORECASE)
print(output)
import re
text = "Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better... |
from board import Board
import pdb
class Game:
def __init__(self, lines, attack_point = 3):
self.board = Board(lines)
self.attack_point = attack_point
self.elf_win = True
def run(self):
turn_count = 0
while not self.turn():
turn_count += 1
return tur... |
class Cell:
def __init__(self, position, cell_type):
self.position = position
self.type = cell_type
self.hit_point = 200
def is_unit(self):
return self.type == 'E' or self.type == 'G'
def is_opponent_of(self, other):
return (self.type == 'E' and other.type == 'G') o... |
words = {"favorite dessert": "apple pie","never eat": "scallop","always have" : "parachute","don't have" :"accident","do this" : "fare","bug" : "flea"}
print(words['bug'])
words['parachute']= 'water'
words['oar']= 'girrafe'
del words['never eat']
for key, value in words.items():
print(key)
|
"""
Let's Learn Python #11 - Overriding & File Mng. - OOP 2 of 3
"""
class BaseClass(object):
def test(self):
print ('ham')
class InClass(BaseClass):
def test(self):
print ("Hammer Time")
i = InClass()
i.test()
b = BaseClass()
b.test()
|
class MyClass(object):
def __init__(self):
self.x = 5
"""
Example:
TypeClass = type("TypeClass", (), {"x":5})
TypeClass TypeClass - these should be the same
(object,) - comma defaults to a tuple
(object, BaseClass, etc)
... |
import argparse
import pandas as pd
from pathlib import Path
parser = argparse.ArgumentParser("Merge the input csv files")
parser.add_argument('csv_files', help="files to merge", type=Path, nargs='+')
parser.add_argument('--output-file', help="Where to write output, to standard out if not given", type=Path)
args = par... |
num = 12345
list_num = list(str(num))
print(list_num)
sum = 0
for i in list_num:
sum += int(i)
print(sum) |
class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
self.storage.append(value)
value_index = len(self.storage) - 1
self._bubble_up(value_index)
def delete(self):
if not self.storage:
return False
elif len(self.storage) == 1:
... |
def find_intersections(w1, w2):
"""
# Return a sorted list of tuples that represent intersection points.
# The sorting order should be from best to worst (e.g. lowest indices
# to highest) Return None if no intersections are found.
"""
intersections = []
for i, x in enumerate(w1):
f... |
import random
import string
strong_or_weak = input("Strong or weak password would you like to choose?")
def passwordgen():
global strong_or_weak
for_weak_password = ['hahika', 'hihike', 'ilovecheese']
if strong_or_weak == "strong":
list_password = []
random_lenght = random.randint(8, 14)
... |
oddEven=50
if oddEven%2==1:
print(str(oddEven)+" is odd!")
elif oddEven%2==0:
print(str(oddEven)+" is even!")
else:
print("This shouldn't run!")
|
"""
vaqt=dt.datetime.now()
print(vaqt.year)
print(vaqt.month)
print(vaqt.day)
print(vaqt.hour)
print(vaqt.minute)
print(vaqt.second)
def vaqt(t)
print(f"soat:{t.hour}:{t.minute} bo`ldi")
vaqt(t)
"""
"""
x=dt.datetime(2021, 7, 15)
print(dt)"""
"""
import datetime
x = datetime.datetime(2021,7,15)
print(x)
"""
"""
i... |
import math
a=int(input("a="))
x=int(input("x="))
y=int(input("y="))
G=(math.cos(2*abs(y+x)-(x+y))**(4*x*x))/(math.atan(x+a)**4*x**5)
print(G) |
"""#matrix = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
B = [[], [], [], [], [], [], [], [], []]
for i in range(3):
for j in range(3):
B[i][j] = int(input(f"[{i}][{j}]="))
print(B)#"""
numberlist = [1,2,3]
numberlist1 = [5,6,7]
numberlist2 = [8,9,10]
print(numberlist)
print (numberlist1)
print(numberlist2) |
import math
y=int(input("y="))
h=int(input("h="))
A=(math.tan(y**3-h**4)+h**2)/(math.sin(h)**2+y)
print(A) |
qidirilayotgan_son=int(input("qidirilayotgan raqamingizni kiriting"))
for i in range(1,11):
if qidirilayotgan_son == i:
print("bor")
break
else:
print("yo`q")
|
"""
def birdanNgacha(n):
if n==1:
print(n)
else:
print(n)
birdanNgacha(n-1)
birdanNgacha(10)"""
"""
def birdanNgacha(k, n):
if n==k:
print(k)
else:
print(k)
birdanNgacha(k+1, n)
birdanNgacha(1, 10)
"""
"""def birdanNgacha(k, n):
if n==k:
... |
if __name__ == '__main__':
arr = []
N = int(input())
for i in range(0,N):
data1 = input().split()
data = data1[0]
ar = data1[1:]
if data != "print":
data += "("+ ",".join(ar) +")"
eval("arr."+data)
else :
... |
def mutate_string(string, position, character):
string = string[:position]+character+string[position+1:]
return string
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new) |
"""
Iteration (looping) in functional languages is usually accomplished
via recursion.
Recursive functions invoke themselves,
letting an operation be repeated until it reaches the base case.
"""
import os.path
def find_available_filename_iter(base):
i = 0
while os.path.exists(f"{base}_{i}"):
i += 1
... |
alpha = 0.0001
initial_b = 0
initial_m = 0
iterations = 1000000
w0 = 0.25
w1 = 0.25
x_points = [2, 4, 6, 7, 8, 10]
y_points = [5, 7, 14, 14, 17, 19]
for i in range(iterations):
summation = 0
summation2 = 0
for j in range(6):
summation += y_points[j] - (w0 + w... |
prefix = set()
prefix.add("Pig")
prefix.add("Cat")
prefix.add("Pig")
prefix.add("Dog")
for dat in prefix:
print(dat)
prefix2 = set(("pig", "Mouse", "Pig", "Dog"))
print(prefix2.intersection(prefix))
print(prefix2.union(prefix))
prefix = frozenset()
prefix.add("Pig")
|
zList = ["This", "is", "a", "Test"]
zPop = zList.pop(0)
print("Popped:", zPop)
print("Result:", zList)
zList = ['Mary', 'had', 'a', 'little', 'lamb!']
zList.pop(-100)
zList.pop(99)
print(zList)
|
zOpts = ("Loop", "Break")
while True:
for ss, opt in enumerate(zOpts, 1):
print(ss, ".)", opt)
zChoice = input("What number? ")
if zChoice is "2":
break
print("Looping ...")
|
"""
Edmond Tongyou
CPSC 223P-01
Tues March 9 14:47:33 2021
tongyouedmond@fullerton.edu
"""
import random
computerScore = 0
ties = 0
userScore = 0
computerChoice = ""
userChoice = ""
while 'Q' not in userChoice:
computerChoice = random.randint(0, 2)
print ("Please input one: (R, P, S, Q) > ", end =... |
tryString = "x {}"
for i in range(1,10):
print(tryString.format(i))
tryString_2 = "x"*5
print("\nx*5: " + tryString_2, end=' ')
print("a b c d")
print("\nwith end='':")
print("\nx*5: " + tryString_2, end='')
print("a b c d")
|
import re
from math import gcd
def lcm(a, b):
return (a*b)//gcd(a, b)
class Moon:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
self.vx, self.vy, self.vz = 0, 0, 0
def apply_velocity(self):
self.x += self.vx
self.y += self.vy
self.z += self.... |
class Base(object):
def test(self):
print("----Base")
class A(Base):
def testA(self):
print("-- A")
class B(Base):
def testB(self):
print("--- B")
class C(A,B):
def testC(self):
print("--C")
c = C()
c.testA()
c.testB()
c.test()
|
class Cat():
def __init__(self,new_name,new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "%s的年龄是:%d" %(self.name,self.age)
def eat(self):
print("猫在吃...")
def drink(self):
print("猫在喝可乐...")
def introduce(self)... |
import getpass
_username = 'alex'
_password = 'abc123'
user = input("请输入用户名:")
password = input("请输入密码:")
if user == _username and password == _password:
print("Welcome user %s login"% user)
else:
print("Wrong username or password") |
from abc import ABC, abstractmethod
class Vehicle(ABC):
def __init__(self, registration_number, color, vehicle_type):
self.registration_number = registration_number
self.color = color
self.vehicle_type = vehicle_type
@abstractmethod
def vehicle_type(self):
pass
def __... |
import webbrowser
class Movie():
"""
Class Movie holds all the necessary information
like Movie's title, storyline, poster and trailer url.
"""
def __init__(self, title, storyline, poster, trailer_link):
self.title = title
self.storyline = storyline
self.poster_... |
from tkinter import *
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
flip_timer = None
current_card = {}
try:
cards_to_learn = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
cards_to_learn = pandas.read_csv("data/french_words.csv")
finally:
cards_to_learn_dict = cards_... |
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.color("white")
self.penup()
self.goto(x=0, y=0)
self.x_move = 10
self.y_move = 10
self.move_speed = 0.05
def move(self)... |
from art import logo
from replit import clear
def calculate(operation, first_num, second_num):
"""Takes two input numbers, a chosen mathematical operation, and performs the operation on the two numbers and returns the output."""
if operation == '+':
output = first_num + second_num
return output
elif oper... |
"""Mendel Second Law Application"""
"""Start with one AaBb individual"""
"""Each generation would only mate with AaBb"""
"""Each generation would have 2 offsprings"""
"""Given the above, P(N (min. number of AaBb organisms)) in the kth generation"""
def Mendel_2nd_Law(K, N):
T = 2**K
P_AaBb = 0... |
"""Ordering different strings of different lengths lexicographically"""
with open("/Users/annatswater/Desktop/rosalind_lexv.txt", "r+") as f:
for line in f:
if line.isdigit() == True:
number = int(line)
else:
char_lst = line.strip().split(" ")
alphabet = "... |
"""Counting the number of each nucleotides in any given string"""
DNA = "ATCGATCG"
A_count = 0
T_count = 0
C_count = 0
G_count = 0
for letter in DNA:
if letter == "A":
A_count+=1
elif letter == "T":
T_count+=1
elif letter == "C":
C_count += 1
else:
G_count += 1
print(A_count, C_count, G_... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error,mean_absolute_error
dataURL='https://raw.githubuserconte... |
def charswap(input):
s = str(input)
if len(str(s)) > 1:
return s[len(s)-1] + s[1:len(s)-1] + s[0]
else:
return s |
import encrypt as enc
import decrypt as dec
import initial as init
key = input("Enter your key (only 8 chars will be used): ")
plainText = input("Enter your plain text (only 8 chars will be used): ")
key = init.key_check(key)
true_len = len(plainText)
if len(plainText) < 8:
plainText += '0'*(56//8-len(... |
from random import randint
player = 50
while True:
coin = randint(1, 2)
if player <= 0 or player >= 100:
break
else:
if coin is 1:
player = player + 9
else:
player = player - 10
if player <= 0:
print("플레이어가 돈을 모두 잃었습니다")
else:
print("플레이어가 100$를 ... |
import collections
import colorsys
import math
import os
import subprocess
import wcag_contrast_ratio as contrast
def choose_tint_color_from_dominant_colors(dominant_colors, background_color):
"""
Given a set of dominant colors (say, from a k-means algorithm) and the
background against which they'll be d... |
arr1 = [[1, 4], [3, 2], [4, 1]]
arr2 = [[3, 3], [3, 3]]
import numpy as np
def solution(arr1, arr2):
arr1 = np.array(arr1)
arr2 = np.array(arr2)
answer = arr1.dot(arr2)
return answer.tolist()
print(solution(arr1, arr2)) |
def solution(nums):
answer = set()
N = len(nums) // 2
for num in nums:
if len(answer) == N:
return N
answer.add(num)
return len(answer)
print(solution([3,3,3,2,2,4])) |
def find_set(s):
new_s = dict()
for i in range(len(s)-1):
check = s[i] + s[i+1]
if check[0].isalpha() and check[1].isalpha():
if check in new_s:
new_s[check] += 1
else:
new_s[check] = 1
return new_s
def union_set(s1, s2, plus_dic):
... |
def solution(record):
answer = []
user_dic = dict()
name_save = []
behavior_save = []
for i in range(len(record)):
one = record[i].split()
if one[0] == "Enter":
user_dic[one[1]] = one[2]
name_save.append(one[1])
behavior_save.append('님이 들어왔습니다.')
... |
def solution(distance, rocks, n):
answer = 0
start = 0
end = distance
rocks.append(distance)
rocks.sort()
while start <= end:
mid = (start+end) // 2
remove_rock = 0
remove_check = 0
for rock in rocks:
if rock - remove_check < mid:
remo... |
def go_right(y, x, t):
if blue[y][x] == 3 or x == 9:
if t == 1:
board[y][x] = 3
blue[y][x-4] = 1
elif t == 2:
board[y][x] = 3
board[y][x-1] = 3
blue[y][x - 4] = 1
blue[y][x - 5] = 1
elif t == 3:
board[y][x] =... |
def solution(s):
stack = []
for i in range(len(s)):
if stack:
if stack[-1] == s[i]:
stack.pop()
continue
stack.append(s[i])
if not stack:
return 1
return 0
print(solution('abccaeeaba'))
print(solution('cdcd')) |
def solution(n):
answer = 0
now = 1
while True:
if now == n:
break
check = 0
for i in range(now, n):
check += i
if check >= n:
break
if check == n:
answer += 1
now += 1
return answer+1
print(solutio... |
total=0
count=0
inFile = open('grade.txt', 'r')
grade = inFile.readline()
while (grade):
total = total + int(grade)
count = count + 1
grade = inFile.readline()
print ("The average is " + str(total))
|
marks = [100,20,20,33,44,55]
marks1 = [100,20,[20,33],44,55]
string = ["hello"]
print (marks1[2])
print (len(string))
str1 = ["hai","sudhakar"]
str2 = ["hai","mnsr"]
print (str1+str2)
print (str1*4)
|
from room import Room
from player import Player
from item import Item
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': R... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.