text stringlengths 37 1.41M |
|---|
'''
https://www.hackerrank.com/challenges/chocolate-feast/problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the chocolateFeast function below.
def chocolateFeast(n, c, m):
if n<c:
return 0
cho = n//c
wrap = cho
while True:
if wrap... |
'''
https://www.hackerrank.com/challenges/electronics-shop/problem
'''
import os
import sys
from itertools import product
def getMoneySpent(keyboards, drives, b):
allout = list(product(keyboards, drives))
new_sum = -1
for val in allout:
if new_sum<sum(val)<=b:
new_sum = sum(val)
... |
'''
https://www.hackerrank.com/challenges/np-sum-and-prod/problem?h_r=next-challenge&h_v=zen
You are given a 2-D array with dimensions X.
Your task is to perform the tool over axis and then find the of that result.
Input Format
The first line of input contains space separated values of and .
The next lines cont... |
class decorateClass(object):
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
print(f"do something before calling function {self.f.__name__}")
self.f(*args, **kwargs)
print(*args, **kwargs)
print("AAA")
@decorateClass
def myFunc():
A=1+1
... |
import math
result = 420
# selection of approximate root a,b
def eqn(x):
return (math.pow(x, 3))-2*x+ 3
for i in range(-3,3):
print(str(i)+"="+str(eqn(i)))
print("Enter the value of a")
a=int(input())
print("Enter the value of b")
b=int(input())
#Finding root
while( result != 0.00 ) :
x=(a+b)... |
from datetime import datetime
# import datetime what is the difference
# ######################## 函数别名(指针)与调用 #########################################
def hi(name='Knight'):
return "hi {}".format(name)
greet = hi # 这里没有加(),因为不是调用函数
# print(greet) # <function hi at 0x0000000002043E18>
# print(hi) ... |
print("{:>4.4f}".format(3.1415926))
print("{:<10.4f},{}".format(3.1415926, 3.1415926))
print("{:<20.4f},{}".format(3.1415926, 3.1415926)) # 对齐方式,宽度,小数位数
print("{:1>20}".format(3.1415926)) # 补齐用的数据,补齐数据的位置,总宽度
print("{:0<20.2}".format(3.1415926)) # 补齐用的数据,补齐数据的位置,总宽度
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, operator
nameTab = []
classTab = []
unique = None
optPath = False
class People:
def __init__(self, name):
self.name = name;
self.listName = []
def getName(self):
return (self.name)
def addRelation(self, name):... |
"""
***************************************************************
* Class: MaxHeap Validation
* Author: Brogan Avery
* Created : 2021-04-13
***************************************************************
"""
class HeapValidator:
def __init__(self, arr, size, i = 0):
self.arr = arr # heap to validate
... |
''''
Author: Brogan Avery
Date: 2020/09/12
Project Title: numPy demo
'''
from numpy import *
#————————————————————————————————————————————————————————————————————————————————————
if __name__ == '__main__':
arr1 = array([[10,15,20],[2,3,4],[9,14.5,18]])
arr2 = array([[1,2,5],[8,0,12],[11,3,22]])
print('Her... |
"""
***************************************************************
* Title: Stack Class
* Author: Brogan Avery
* Created : 2021-02-06
* Course: CIS 152 - Data Structure
* Version: 1.0
* OS: macOS Catalina
* IDE: PyCharm
* Copyright : This is my own original work based on specifications issued by the course instructor... |
"""
***************************************************************
* Class Name: Node
* Author: Brogan Avery
* Created: 2021-03-18
***************************************************************
"""
from queue import Queue
class Node:
def __init__(self, iData = None, sData = None):
self.sData = sData # st... |
"""
***************************************************************
* Title: first come first serve tickets
* Author: Brogan Avery
* Created : 2021-02-21
* Course: CIS 152 - Data Structure
* Version: 1.0
* OS: macOS Catalina
* IDE: PyCharm
* Copyright : This is my own original work based on specifications issued by th... |
"""
***************************************************************
* Class Name: Graph
* Author: Brogan Avery
* Created: 2021-03-25
***************************************************************
"""
class Graph:
def __init__(self, numNodes):
self.numNodes = numNodes # number of nodes on the graph
... |
"""
***************************************************
Title: file IO
Author: Brogan Avery
Created: 2020-02-25
Description :
OS: macOS Catalina
Copyright : This is my own original work based on specifications issued by the course instructor
***************************************************
"""
def write_to_file(som... |
# isomorphism example
test_case = 3
if test_case == 1:
g = {
'A': ['B', 'C'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D', 'F'],
'D': ['B', 'C'],
'E': ['F'],
'F': ['C', 'E']
}
h = {
'1': ['2', '3'],
'2': ['1', '3'],
'3': ['1', '2']
}... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 25 18:41:32 2020
https://towardsdatascience.com/natural-language-processing-count-vectorization-with-scikit-learn-e7804269bb5e
@author: acorso
"""
from sklearn.feature_extraction.text import CountVectorizer
# To create a Count Vectorizer, we simply need to ins... |
# In this section I am studying reading and writing files using python.
# I downloaded the first gene from E. coli and saved it as gene.fa
# reading files
my_file = open("gene.fa")
# It is not the same interaction of strings.
print(my_file)
# <open file 'gene.fa', mode 'r' at 0x10a7ac660>
# So working with files nee... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author:sisul
# time: 2020/7/7 17:39
# file: 数学运算、逻辑运算和进制转化相关的 16 个内置函数.py
'''数学运算'''
#len(s)
dic = {'a':1,'b':3}
print(len(dic))
#max(iterable,*[,key,default])
print(max(3,1,4,2,1))
print(max((), default=0))
di = {'a':3,'b1':1,'c':4}
print(max(di))
a... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author:sisul
# time: 2020/7/14 9:27
# file: Python对象间的相等性比较等使用总结.py
'''
Python,对象相等性比较相关关键字包括is、in,比较运算符有==。
is判断两个对象的标识号是否相等
in用于成员检测
==用于判断值或内容是否相等,默认是基于两个对象的标识号比较
也就是说,如果a is b为 True且如果按照默认行为,意味着a == b也为True
'''
'''
is判断标识号是否相等
is比较的是两个对象的标识号是否相等,python... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author:sisul
# time: 2020/7/14 15:07
# file: yield关键字和生成器.py
'''
yield
理解yield,可结合函数的返回值关键字return,yield是一种特殊的return。说是特殊的return,是因为执行遇到yield时,立即返回,这是与return的相似之处。
不同之处在于:下次进入函数时直接到yield的下一个语句,而return后再进入函数,还是从函数的第一行代码开始执行。
带yield的函数是生成器,通常与next函数结合用。下次进入函数,意思是使用next函... |
## The script asks a number from the user, and prints all the numbers smaller than this number that are primes:
def is_number_prime(number):
'''
Checks whether a number is prime (returns True) or not (returns False).
'''
is_prime = True
for i in range(2,number):
if number%i==0:
... |
mylist = [1,2,3,4,5,6,7,8]
mylist.append(9)
print(mylist)
mylist.pop()
print(mylist)
#functions
def say_hello(name='Name'):
"""
:return:this function will print hello...just that nothing else...this is a stupid function..this is for
people who does not understand my code
"""
return 'hello ' +n... |
# Ard van Balkom, 9-2-19
# Problem 4. Asks user for a positive integer. then output the successive value.
# If current value is even, then it is divided by 2. If current value is odd, it is multiplied by 3 and 1 is added. If current value is 1, the program ends.
while True: # Run a while loop that will run indefinitel... |
'''Define political office model and its methods. '''
import datetime
OFFICE_DB = []
class OfficeModel:
"""
Description:Handle all the operations related to political offices.\n
"""
def __init__(self,office_name, office_type):
"""
Description:Define the instance variables.\n
... |
class MPNeuron:
def __init__(self):
self.w = []
self.x = []
for i in range(3):
self.w.append(1)
self.x.append(1)
self.threshold = 2.5
def MP_Neuron_Input(self,n,threshold):
self.w = []
self.x = []
for i in range(n):
... |
list1=[1,2,3,4,5]
list2=[8,9,10,11,12]
list1.append(6)
print(list1)
list2.append(13)
print(list2)
print(list1+list2)
|
import random
def headOrTail(max):
head = False
tail = False
headCount = 0
tailCount = 0
for num in range(1, max):
coin = random.randint(0, 1)
isHead = ""
isTail = ""
if coin == 0:
head = True
tail = False
isHead = "It's a head!"
... |
#This is a program which will tell the age
age =input("Please enter your age or the year you borned: ")
count = len(age)
if(count==2 or count==3):
age = int(age)
if(age==0 or age<0):
print("What the fuck man! You are not born yet.")
elif(age>100 and age<200):
print("You might be the oldest man alive on earth"... |
# Summation of primes
from math import sqrt
# using check primes algorithm
def check_primes(n):
for i in range(2, int(sqrt(n))+1):
if n % i == 0:
return False
return True
# using Sieve of Eratosthenes algorithm
def getPrimes(limit):
numList = [x for x in range(2, limit+1)]
primeIdx... |
class LinkedList:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __init__(self):
self.head = None
self.count = 0
def prepend(self, value):
self.head = LinkedList.Node(value, next=self.head)
self.count... |
def binarySearch(lst, target):
left, right = 0, len(lst)-1
while left <= right:
mid = (right - left)//2 + left
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
|
# Amicable number
from math import sqrt
def divisors(n):
div = [1]
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
if n // i == i:
div.append(i)
else:
div.extend([i, n//i])
return div
def isAmicable(n):
divSum = sum(divisors(n))
i... |
#In this section We are going to learn about Objects or Dictonary
# If you have Previous Progaming background you have learn something about objects
# if not dont woory you will learn in this section
myObj = {'name':'Ghayyas','age':21,'study':'Software Engeering'};
print myObj; #Return all the objects
#let says w... |
"""
Module: Snake Iteration 7
Author: Koby (Beaulieu|Soden)
University of San Diego
Description:
A Python implementation of Greedy Snake, using Tkinter, and implemented
using the model-view-controller design pattern.
Iteration 6:
Final iteration of the snake program. This last iteration implements the e... |
#########################类
'''class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print(self.name.title()+'is now sitting')
def roll_over(self):
print(self.name.title()+'rolled over!')'''
'''def city_s(city,country,population=''):
if popul... |
import re
def snake_case(text):
"""
Used for converting paths and such to a snake case format.
"""
no_symbol = re.sub('[^A-Za-z0-9]', '_', text)
no_duplicate = re.sub('[_]{2,}', '_', no_symbol.lower())
return re.sub('(^_|_$)', '', no_duplicate)
|
inputRow = int(input("Enter row : "))
star = 1
space = " "
for i in range(inputRow):
print(space*(inputRow-(i+1))+"*"*(i+star))
star += 1
|
"""Helper methods for formatting and manipulating tracebacks"""
import traceback
def format_exception_info(exception_info_tuple, formatter=None):
if formatter is None:
formatter = traceback.format_exception
exctype, value, tb = exception_info_tuple
# Skip test runner traceback levels
w... |
#Code for disabling sys modules that will be inserted into the beginning of the data the user inputs
insert = """
import sys
for x in sys.modules:
sys.modules[x] = None
"""
#Keywords that are not allowed
badList = [
'__builtins__', 'open', 'eval', 'execfile', 'import', 'exec','write', 'read',
]
#place the f... |
#fibonacci numbers from 1-10.
def fib(x):
if x == 0:
return 0
elif x == 1 or x == 2:
return 1
else:
return fib(x-1)+ fib(x-2)
for x in range (0,10):
print fib(x)
|
class Parent():
def __init__(self, last_name, eye_color):
print "Parent constructor called"
self.last_name = last_name
self.eye_color = eye_color
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
print "Child constructor called"
Parent.__init__(self, last_name, eye_color)
s... |
#create integer set from list
list1=[1,2,3,4,5]
b=[4,5]
s=set(list1)
print("integer set of list is : ")
print(s)
#character set
ch=set("Hello, how are you 5?")
print("character set of list is : ")
print(ch)
#set operation
print("Original Set")
print(s)
print("After removing an element from : ")
s.remove(1)
print(s)... |
from tkinter import *
class myscrollbar:
def __init__(self, root):
#text widget
self.t=Text(root,width=70,height=15,wrap=NONE)
#text crowd
for i in range(50):
self.t.insert(END,"This is some text")
#text to root window at top
... |
#class
class Car:
def __init__(self, components):
self.components = components
def __repr__(self):
return f'Car({self.components!r})'
@classmethod
def carA(cls):
return cls(['suzuki','duccatti'])
@classmethod
def carB(cls):
return cls(['Maruti','Hyundai'])
#sta... |
#zero division
a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
try:
c=a/b
print(c)
except ZeroDivisionError as args:
print("Exception:- ",args)
else:
print("Successfully division done")
#value error
try:
a=int(input("Enter no : "))
except ValueError as args:
print("Exception:- ... |
class Error(Exception):
"""Base class for exception"""
class ValueSmallError(Exception):
"""Raised for very small value"""
pass
class ValueLargeError(Exception):
"""Raised for very large value"""
pass
number=10
while True:
try:
num=int(input("Enter Number : "))
if num<number:
... |
def print_two(*args):
for word in args:
print(word)
print_two("AAA","BBB","CCC","DDD")
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
print_two_again("Zed","Shaw")
def print_none():
print("I got nothin'.")
print_none() |
"""
順列とはモノの順番付きの並びのことである. たとえば, 3124は数 1, 2, 3, 4 の一つの順列である. すべての順列を数の大小でまたは辞書式に並べたものを辞書順と呼ぶ. 0と1と2の順列を辞書順に並べると
012 021 102 120 201 210
になる.
0,1,2,3,4,5,6,7,8,9からなる順列を辞書式に並べたときの100万番目はいくつか?
"""
import math
# 最初の数字を決定させ、その値とそうなるための下限値を返す関数
def check_first_digit(number_list, order):
first_digit_rank = 0
for ... |
"""
ピタゴラス数(ピタゴラスの定理を満たす自然数)とは a < b < c で以下の式を満たす数の組である.
a^2 + b^2 = c^2
例えば, 32 + 42 = 9 + 16 = 25 = 52 である.
a + b + c = 1000 となるピタゴラスの三つ組が一つだけ存在する.
これらの積 abc を計算しなさい.
"""
import math
if __name__ == '__main__':
a = 1
b = 2
summary = 0
combination_list = []
# aは最小のため、333までを考えればよく、bはcより小さいため、500ま... |
# Problem Statement
#
#
# Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}.
#
#
# make_pi() → [3, 1, 4]
def make_pi():
import math
return [int(num) for num in str(int(math.pi * 100))]
print(make_pi()) |
# user_search_books.py
# --------------------
# list books in books table in project1 database where title contains 'irl'
"""
Example:
Enter anything you might know about the book
Just his 'Enter' to skip any field you don't know anything about
title: irl
author: ian
year: 20... |
import re
# Class User
class User():
Name = "John Doe" # Default name is John Doe starting out
email = "name@something.com" # email address of user
Nickname = "Slick" # Nickname of user
# constructor of the Character object.
def __init__(self, name, email, ni... |
import tkinter as tk
from tkinter import ttk, N, E, W, S
class Display:
def __init__(self, rows, columns):
self.root = tk.Tk()
self.root.title("Robot Playground")
for c in range(columns):
self.root.columnconfigure(c, weight=1)
for r in range(rows):
self.root... |
#!/usr/bin/python3
"""JSON Class"""
class Student:
"""Class student json"""
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
if attrs is None:
return self.__di... |
#!/usr/bin/python3
"""Append to a file"""
def append_write(filename="", text=""):
"""function that append in a file and return the number of chars written"""
with open(filename, mode='a', encoding='utf-8') as a_file:
written = a_file.write(text)
return written
|
#!/usr/bin/python3
from sys import argv
def check_sol(list_s, queen, n):
"""check if the queen position is validate to the list_s"""
cnt = 0
if len(list_s) == 0:
return(True)
while cnt < len(list_s):
f, c = list_s[cnt][0], list_s[cnt][1]
if f == queen[0] or c == queen[1]:
... |
#Justin Farquharson
#8/31/2021
#Day 3 - Review, Math, Control Statements
print(3%2)
print(4%2)
print(5%2)
print(6%2)
print(7%2)
number = 12.3456789
print("The value:", "%.2f"%number)
money = int(input("How much money do you have?\n"))
#Interger Division - Always rounds down.
tickets = money//10
#... |
#Justin Farquharson
#09/26/2021
#COP 2500C
#Video Game
import random
games = 0
groups = 0
while(games < 20):
size = random.randint(1,4)
#print(size)
groups = groups+1
print("Visiting Group #", groups)
#This will determine if there's space for user to play with this group
if (s... |
run = int(input("How many days would you like to track?\n"))
x = 0
while(run != 0 and run >= 0):
run = run - 1
miles = int(input("How many miles did you run?\n"))
if(miles < 0):
print("Please use positive whole numbers")
run = run + 1
miles = miles - miles
x = x ... |
#!/usr/bin/env python
'''
Created by Oleksandra Baga
Write a PID-controller which makes sure that the model car is able to achieve and maintain a
certain velocity, which comes as an input and is specified in meters per second. Use the
pulse-sensor in the vehicle as a sensory feedback. The output of the controller shal... |
def specialMultiply(n, m):
#This function makes adjustments for big multiplications.
#It is just AWESOME. Wrapping up the answer everytime it crosses the given limit.
if n > 1000000007:
n = n % 1000000007
n = n * m
n = n % 1000000007
return n
def possibilities(W):
#For the given word, this function calculate... |
#Вариант, если сравниваемое значение равно одному символу
def get_less(seq=0,number=0):
seq = str(seq)
sm = " "
for i in range(len(seq)):
if int(seq[i]) < number:
sm += seq[i]
return int(sm)
a = int(input("Enter sequence: "))
b = int(input("Enter number for compare: "))
newseq = g... |
def ask_yes_no(question):
response = None
while response not in ("y","n"):
response = input(question).lower()
return response
#answer = ask_yes_no("\nPlease, enter 'y' or 'n': ")
#print("Thnx for ypur answer ",answer)
def birthday(name, age):
print("Happy birthday", name, ". Now you are",age... |
#Вариант, если сравниваемое значение более одного символа
def get_less(seq=0,number=0):
seq = str(seq)
number = str(number)
sm = " "
for i in range(0, len(seq), len(number)):
c = i + len(number)
if int(seq[i:c]) < int(number):
sm += seq[i:c]
return int(sm)
a = int(inp... |
print("Enter numbers")
mx = 0
'''
while True:
a = int(input("Enter number: "))
if a == 13:
break
elif a > mx:
mx = a
'''
a = 0
while a != 13:
a = int(input("Enter number: "))
if a > mx:
mx = a
print("Maximum:", mx)
|
# functions
myString = "Hello World"
print(myString)
x = len(myString)
print(x)
# this is a procedure because nothng is returned
def myprocedure(printme) :
print(printme)
myprocedure("Hello World")
def xtimesprint(printme, howoften) :
returnstring = ""
for x in range(howoften) :
... |
# If ... Elif ... Else ... EndIf
a = 5
b = 4
print(a,b)
if a > b :
print(a, " is greater than ", b)
elif a == b :
print(a, " equals ", b)
else :
print(a, " is less than ", b)
|
with open("input.txt", "r") as input_file:
data = input_file.readlines()
# Strip \n and stuff from the lines
data = [s.strip() for s in data]
count = 0
# https://stackoverflow.com/questions/38138842/how-to-check-whether-two-words-are-anagrams-python
def is_anagram(a, b):
return sorted(a.lower()) == sorted(b.... |
import array
data = None
with open("input.txt", "r") as input_file:
data = input_file.read().replace("\n", "")
print("Received data from input file:", data)
index = 0
length = len(data)
arrayList = array.array('i')
for number in data:
number = int(number)
print("Character:", number)
try:
ne... |
#!/usr/bin/env python
""" Extract data from EXCEL to fill-in JINJA2 template
This script is a tool to convert data from Excel file to YAML to fill-in a Jinja2 template.
YAML structure is the following:
SHEET_NAME:
- COLUMN#1: value ROW#1 / COLUMN#1
COLUMN#2: value ROW#1 / COLUMN#2
...
- COLUMN#1: value R... |
import unittest
from src.game.game import *
from src.game.map import *
from src.game.tests.test_game import create_players
class TestMap(unittest.TestCase):
def setUp(self) -> None:
self.game = Game()
create_players(self.game, 3)
self.game.start_game()
def test_at_game_start_every_pla... |
import random
from src.game.room import Room
from src.game.zone import Zone
class Map:
def __init__(self, players, rooms_per_player=3, room_connections=2):
self.rooms_per_player = rooms_per_player
self.nb_generate_room_connections = room_connections
self.rooms = self.generate_rooms(player... |
class BlackjackHand:
# Creates Hand List
def __init__(self):
self.hand = []
# Adds card to hand
def add_card(self, new_card):
self.hand.append(new_card)
# Prints Cards as a string
def __str__(self):
cards = ""
for card in self.hand:
cards += str(card) + "... |
initial_balance = 1000
interest_rate = .05
balance_after_first_year = initial_balance + (initial_balance * interest_rate)
balance_after_second_year = balance_after_first_year + (balance_after_first_year * interest_rate)
balance_after_third_year = balance_after_second_year + (balance_after_second_year * interest_r... |
###############################
# PROGRAMMING ASSIGNMENT #2 #
###############################
# IMPLEMENTING QUICKSORT
# The file QuickSort.txt contains all of the integers between 1 and 10,000 (inclusive, with no repeats) in unsorted
# order. The integer in the ith row of the file gives you the ith entry of an inpu... |
###########################
# WEEK 4: SHORTEST PATH #
###########################
# This is my own attempt to compute the shortest path between two vertices of a graph using Breadth-First Search (
# BFS). I will use an adjacency list representation of a graph.
# NOTE: This is NOT Dijkstra's Algorithm, but it's sort... |
"""
Date: 2/27/2020 5:59 PM
Author: Achini
"""
def check_negation(text, NEGATION_MAP):
"""
Utility function to check negation of an emotion
:param text: text chunk with the emotion term
:return: boolean value for negation
"""
neg_word_list = NEGATION_MAP
neg_match = False
for neg_word ... |
x = input("enter the alp:")
if(x=='A' or x=='a' or x=='E' or x=='e' or x=='I' or x=='i' or x=='O' or x=='o' or x=='U' or x=='u' ):
print(x, "Vowels")
else:
print(x, "Consonant")
|
intro = input("Write Something About Your Self: ")
chrcount = 0
wordcount = 1
for i in intro :
chrcount = chrcount + 1
if(i==" "):
wordcount = wordcount + 1
print("No Of Words in Your indtroduction")
print(wordcount)
print(chrcount) |
# Weather Forecasting Assignment
class Weather:
# grid properties
grid = []
width = 0
height = 0
max_label = '@'
storm_label = '&'
cloud_label = '.'
default_label = '#'
# what we need
clusters = []
def __init__(self, user_input=''):
# Get user input
if no... |
#! /usr/bin/env python
import numpy as np
import matplotlib as mpl
def show_array (x):
""" Display the basic properties of the array.
"""
print '-- Array dimensions =', x.ndim
print '-- Array shape =', x.shape
print '-- Array datatype =', x.dtype
print '-- Array data =\n', x
## G... |
def max_profit(prices):
"""Given an array with prices of a given stock per day, if you are
only permited to complete one transaction (buy one and sell one share of stock), design an algorithm to find the maximum profit
Example:
input = [7,1,5,3,6,4]
output = 5
"""
#My first attempt at the pr... |
#imports the ability to get a random number (we will learn more about this later!)
from random import *
#Create the list of words you want to choose from.
aList = ["carrot", "orange", "yellow", "blue", "water", "apple", "lollypop", "cake", "fruit", "mango"]
adjetives = ["kind", "smart", "loving", "caring", "mean", "fu... |
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(2))
def calc_total(list):
sum = sum(list)
for num in list:
sum += num
return sum
|
from unittest import TestCase
from accounting_stats import AccountingStats
class TestAccountingStats(TestCase):
"""This is a test class to test the AccountingStats class"""
def setUp(self):
"""Initialize setup object"""
self.stats = AccountingStats(5, 100, 150000)
def test_valid_constru... |
print("input a number")
number = int(raw_input("number: "))
for x in xrange(1,13):
result = number * x
print(str(number) + " x " + str(x) + " = " + str(result))
|
class node:
def __init__(self,val):
self.val =val
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert(self,val):
x = self.head
if(x==None):
self.head = node(val)
else:
while(x.next!=None):
... |
from decimal import Decimal
def rmb(x):
return float(Decimal(x).quantize(Decimal("0.00")))
def calculate(base_commission_percent=0.13, buy_stock_num=100, buy_price=1, sell_price=2):
base_commission = 5
base_commission_percent = base_commission_percent / 1000
stamp_duty = 0.1 / 100
# 印花税费
tra... |
import numpy as np
from .ReadData import readMatrix, readVector
import time
'''
Método que calcula (haciendo uso del paralelismo) la solución a un sistema de ecuaciones lineales por medio del método iterativo de Jacobi.
Entradas: Matriz Diagonalmente Dominante A, vector independiente b, tolerancia y maximo de iterac... |
from heapq import heapify, heappop, heappush
def solution(jobs):
answer = 0
cur, cnt = 0, len(jobs)
heap = []
heapify(jobs)
while jobs or heap:
while jobs:
if jobs[0][0] > cur:
break
enter, processing = heappop(jobs)
heappush(heap, (process... |
from itertools import combinations
def isPrime1(n): # 무식 소수
if(n<2):
return 0
for i in range(2,n):
if(n%i==0):
return 0
return 1
def isPrime2(n): # 에라토스테네스의 체
a = [False,False] + [True]*(n-1)
primes=[]
for i in range(2,n+1):
if a[i]:
primes.append(i)
for j in ra... |
import heapq
def solution(n, s, a, b, fares):
graph = {}
minFare = float('inf')
for i in range(n):
graph[i+1] = {}
for node1, node2, weight in fares:
graph[node1][node2] = weight
graph[node2][node1] = weight
for i in range(1,n+1):
middle_distance = dijkstra(grap... |
def operate(a, b, c):
if c == '*':
return a*b
elif c == '-':
return a-b
else:
return a+b
def solution(expression):
number_list = []
operate_list = []
index = 0
for idx, val in enumerate(expression):
if idx == len(expression)-1:
number_list += [in... |
def solution(s):
answer = 0
l = len(s)
for i in range(l):
after = s[:i]
before = s[i:]
string = before+after
if iscorrect(string):
answer += 1
return answer
def iscorrect(s):
symbols = {
'(': ')',
'{': '}',
'[': ']',
}
op... |
def dfs(numbers,index,result,target):
if len(numbers) == index:
return 1 if target == result else 0
return dfs(numbers, index+1, result + (numbers[index]*-1),target) + dfs(numbers, index+1, result + (numbers[index]),target)
def solution(numbers, target):
return dfs(numbers, 1, numbers[0]*-1, t... |
record = ["Enter uid1234 Muzi", "Enter uid4567 Prodo",
"Leave uid1234", "Enter uid1234 Prodo", "Change uid4567 Ryan"]
def solution(record):
answer = []
order_list = []
people_list = {}
for i in record:
temp = i.split()
if temp[0] == "Change":
people_list[temp[1]] ... |
def solution(s):
s_list = []
answer = 0
for i in range(len(s)):
s_list.append(s)
s = s[1:]+s[0]
for i in s_list:
stack = []
for j in i:
if j == '[' or j == '{' or j == '(':
stack.append(j)
else:
if stack:
... |
from heapq import heappush, heappop
from collections import defaultdict
def solution(N, road, K):
graph = defaultdict(lambda: {})
answer = 0
for a, b, c in road:
print(a, b, c)
graph[a][b] = c
graph[b][a] = c
for a, b, c in road:
if graph[a][b] > c:
graph[a]... |
import random
import tkinter
class Snake(tkinter.Canvas):
def __init__(self, master=None):
#Lamada al constructor de su padre
super().__init__(master)
#Identifica si se movio de posicion recientemente
self.movio = False
#Caracter usado para la cabeza de snake
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.