text stringlengths 37 1.41M |
|---|
import math
import numpy as np
from .uniform.uni_gen import Uni_generator
class Binom_gen():
"""
Generate binomial distribution
"""
def __init__(self, m, p):
"""
Inputs:
- m: Integer count of experiments
- p: Float probability of success
"""
self.m = m
... |
from it import it
def test_equals():
eq = it == 5
assert eq(5), "5 equals 5"
assert not eq(4), "4 does not equal 5"
def test_it_less_than():
lt = it < 5
assert lt(4), "4 is less than 5"
assert not lt(6), "6 is not less than 5"
assert not lt(5), "5 is not less than 5"
def test_it_less_t... |
numbers = [2, 3, 4, 6, 3, 4, 6, 1]
# append adds to the end of the list
# numbers.append(20)
# insert allows us to insert new items at the index we set
# second value is the value we wish to add to the list
# numbers.insert(0, 10)
# .remove will remove the value we want which we pass through
# numbers.remove(5)
# to re... |
def emoji_convertor(sentence):
emojis = {
":)": "😀",
":(": "☹️",
":'(": "😢",
":|": "😐",
":p": "😜"
}
output = ""
words = sentence.split(" ")
for word in words:
output += emojis.get(word, word) + " "
return output
sentence = input('>')
print... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 26 09:50:10 2021
@author: Carl-Michael
"""
def prime_factors(number):
#print('works')
factors = list()
divisor = 2
while divisor <= number:
if number % divisor == 0:
factors.append(divisor)
number = number / d... |
import nltk
f = open('output.txt').read()
wtokens = nltk.word_tokenize(f)
wtokens = [word.lower() for word in wtokens if word.isalpha()]
# Word Tokenization. Words are separated from each other.
for t in wtokens:
print(t)
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# collections--- in python
# deque ---is double ended queue
# append, appendleft, extend, extendleft, pop , popleft,
# FIFO : First in First out(queue)
# LIFO : drque
# Counter - Gives you a count of each items in the container with key value structure
# OrderedDic... |
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.current = 0
self.storage = [None]*capacity
def append(self, item):
# Set the passed in item to evaluate to the current item in storage.
self.storage[self.current] = item
# If the current value is less than the ove... |
def nombreDivisibles (liste1, n):
listeDivisible = []
for each in liste1 :
if (each % n == 1):
listeDivisible.append(each)
return listeDivisible;
liste1 = [1,2,3,4,5]
n = 2
resultat = nombreDivisibles(liste1,n)
print (resultat)
|
class Poly :
def __init__(self, x,y,z):
self.x = x
self.y = y
self.z = z
def coeff(self):
coeff = [self.x,self.y,self.z]
return coeff
def evalue(self,x):
resultat = self.x+self.y*x+self.z*(x*x)
return resultat
p = Poly(3,4,-2)
print(p.coe... |
def toutEnMajuscule(L):
resultat = []
for each in L:
resultat.append(each.upper())
return resultat
L = ["Python", "est", "un", "langage", "de", "programmation"]
print(toutEnMajuscule(L))
|
class CompteBancaire :
def __init__(self, nom, solde=0):
self.nom = nom
self.solde = solde
def __repr__(self):
return {"compte de ":self.nom,"solde ":self.solde}
def retrait(self,nb):
self.solde = self.solde - nb
def depot(self,nb):
self.solde = self.sol... |
s = input("Saisir une phrase: ")
if (s == ""):
print ("la chaine de caractere est vide ")
s = list(s)
if (not s):
print("la liste est vide")
|
#!/usr/bin/env python
import math
import numpy as np
from PIL import Image
import tifffile
# *************************************************************
# * From Photography Notebook *
# *************************************************************
# ======================= white_bal... |
'''
Shreyash Shrivastava
1001397477
CSE 6363
'''
import math
# Height Weight Age Class
D = [ ((170, 57, 32),'W'),
((192, 95, 28),'M'),
((150, 45, 30), 'W'),
((170, 65, 29), 'M'),
((175, 78, 35), 'M'),
((185, 90, 32), 'M'),
((170, 65, 28), 'W'),
((155, 48, 31), 'W'),
((160, 55, 30), 'W'),
((182, 80, 30), ... |
#!/usr/bin/python
number = 20
guess = int(input('Enter an integer: '))
if guess == number:
print ('you guessed it.')
elif guess < number:
print('No, it is higher than that')
else:
print('No, it is lower than that')
|
# Подключение библиотек
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
#Создание основного фрейма
root = tk.Tk()
root.title('Список дел')
root.geometry("500x400")
#Инициализация массива для добавления заданий
tasks = []
#Функция добавления задания
def addTask():
word = input_entry.ge... |
# coding: UTF-8
# No.? Python Study 2015/07/?
# タプル (変更できない)
a = (2, 5, 8)
# len + * []
print len(a) # 3
print a * 3
# a[2] = 10 変更できない
# タプル <> リスト
b = list(a)
print b
c = tuple(b)
print c
|
import numpy as np
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; print(x) # 2차원 배열 생성 후 출력
arr_x = np.array(x); print(arr_x) # Numpy의 ndarray로 변환 후 출력
arr_y = np.eye(3); print(arr_y) # 주 대각 성분이 1 나머지가 0인 단위 행렬 생성 후 출력
dot_xy = np.add(arr_x, arr_y); print(dot_xy) # 행렬 덧셈 |
class Country():
"""A model for a country
"""
def __init__(self, name, factor_endowments, technologies):
"""Initialize instance variables.
:param name: country name
:type name: str
:param factor_endowments: country's factor endowments
:type factor_endowments: dict
... |
nums = [10, 20, 30, 40]
for i in range(len(nums)):
nums[i] = nums[i] * 10
print(nums)
|
# def check(n):
#
# for i in range(len(n)):
# if n[i]%2==0:
# print("this even number:",n[i])
# else:
# print("this number is odd:",n[i])
# n=[10,20,30,50,60,77]
# check(n)
# def count1(string,string2="a"):
# count=0
# for i in string:
# if i in st... |
# str1="venkayesh"
# count=0
# for i in str1:
# count=count+1
# new=str1[0:2]+str1[-2:]
# print(new)
str1=["venkatesh","sai","reddy","manoj","venkatesh"]
str2="venkatesh"
count=0
for i in range(len(str1)):
if str2==str1[i]:
count+=1
print(count)
|
class rectangle:
def __init__(self,breadth,height):
self.breadth=breadth
self.height=height
def area(self):
return self.breadth*self.height
obj=rectangle(10,20)
print(obj.breadth)
print(obj.height)
print(obj.area()) |
from tkinter import *
from PIL import ImageTk , Image
root=Tk()
root.title("ESCAPE ROOM GAME")
books= ImageTk.PhotoImage(Image.open("book1.jpg"))
clocks2= ImageTk.PhotoImage(Image.open("clocks1.jpg"))
key1= ImageTk.PhotoImage(Image.open("key1.jpg"))
key2= ImageTk.PhotoImage(Image.open("key2.jpg"))
key3= Ima... |
import openpyxl
def make_invoice(invoice_id):
"""
Receives an invoice id as parameter, obtains invoice data from spreadsheet
'sales_data.xlsx', and appends an invoice with the following format to
'invoice.txt':
Andrew Wang (client ID: 124)
Invoice # 266... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This is a simple python program to help manage email address
that are set up using mysql. This program allows you to
add/delete email addresses, add new domains, and add
new aliases.
'''
import MySQLdb as mdb
import os
def db():
data = open('/path/to/mysqlinf... |
import random
def shuffle(mylist):
new_list = []
while len(mylist) > 0:
change = random.randrange(len(mylist))
new_list.append(mylist[change])
mylist.remove(mylist[change])
return new_list
mylist = [5,3,8,6,1,9,2,7]
print(mylist)
x = shuffle(mylist)
print(x)
|
class Solution:
def mySqrt(self, x):
if x == 0 or x == 1:
return x
mid = int(x/2)
while mid > 0:
if mid * mid == x:
return mid
elif mid * mid > x:
mid = int(mid/2)
else:
break
w... |
class Solution:
def strStr(self, haystack, needle):
lenNeedle = len(needle)
lenHaystack = len(haystack)
if lenNeedle == 0:
return 0
if lenHaystack == 0 or lenHaystack < lenNeedle:
return -1
for i in range(len(haystack)):
if i + lenNeedle >=... |
from karel.stanfordkarel import *
"""
File: EndpointCounter.py
------------------------
In this problem, Karel is in the top left corner of a
square world. Karel needs to make his way down to a staircase
at the bottom left corner, and from there, he needs to place
the same number of beepers on each step as t... |
while True:
a = int(input("lotfa adadi ra vared konid:"))
b = '*'
print(b * a)
|
"""
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
"""
def countBob(s):
'''
This function counts the number of times the term 'b... |
x = 1
y = 0
while x <= end:
y = y + x
x += 1
print y
|
def fib(n):
i = 1
x = [0,1]
while len(x) < n:
x.append(x[i] + x[i-1])
i += 1
return(x)
# alternatively
def fibon(n):
a = b = 1
result = []
for i in range(n):
result.append(a)
a, b = b, a + b
return result
# generator version, does not block as much memor... |
from abc import ABC, abstractmethod
class AbstractClassExample(ABC):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
def do_something(self):
pass
class DoAdd42(AbstractClassExample):
def do_something(self):
return self.value... |
def displayTitle(title):
separator = "=" * 50
print(separator + " " + title + " " + separator)
"""
나무를 1 찍음
나무를 2 찍음
나무를 3 찍음
나무를 4 찍음
나무를 5 찍음
나무가 넘어감
while문 밖
"""
treeHit = 0
while treeHit < 5:
treeHit = treeHit + 1
print("나무를 %d 찍음" % treeHit)
if treeHit == 5:
print("나무가 넘어감")
print... |
try:
print(4 / 0)
except:
print("Exception occur..")
try:
4 / 0
except ZeroDivisionError as e:
print(e)
try:
f = open("foo.txt", "r")
except FileNotFoundError as e:
print(str(e))
else:
data = f.read()
f.close()
finally:
print("finally is called..")
try:
f = open("foo.txt", "r"... |
"""
문자열 자료형
"""
lineSeparator = "=" * 50
# == 문자열 생성
str1 = "Hello World"
str2 = 'Python is fun'
str3 = """Life is too short, You need python"""
str4 = '''zaccoding'''
print(str1)
print(str2)
print(str3)
print(str4)
# == 문자열에 ' 포함
food = "Python's favorite food is perl"
# Python's favorite food is perl
print(food)
... |
# -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from triangle_classify import classify_triangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unitte... |
import random
def randomFig():
figure = random.randint(1, 20)
return figure
def welcome():
print ("Welcome to guess the number game! Guess the number between 1 and 20! You have 7 guesses! Take a Guess:")
def events(figure):
while(guesses<=10):
if guesses==10 :
print("Gameover")
br... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 20:19:08 2017
@author: chao_lu
"""
# Dependencies
import csv
#input and output files
file_to_load = "election_data_2.csv"
file_to_output = "election_data_2.txt"
# Read the csv and convert it into a list of dictionaries
Candidates=[]
with ... |
"""This module contains Movie class"""
import re
class Movie(object):
"""Class to encapsulate Movie data for display in HTML page"""
def __init__(self, title, poster_image_url, trailer_youtube_url, release_year, rating):
"""Initialization method for Movie class"""
self.title = title
se... |
def main():
ogrenci_no=input('Ogrenci Numaranızı Giriniz')
ogrenci_no=int(ogrenci_no)
arkadaslar_dosyasi=open('arkadaslar.txt','w')
ogno=ogrenci_no%10
for sayac in range(1,ogno+1):
isim=input('İsim Giriniz: ')
telefon=input('Telefon giriniz: ')
arkadaslar_dosyasi.write('İsim:... |
def smallest(a,k):
for i in range(0,n):
min=i
for j in range(i+1,n):
if(a[j]<a[min]):
min=j
temp=a[i]
a[i]=a[min]
a[min]=temp
print("k th smallest is: ",a[k-1])
n=int(input("enter the num of elements in array: "))
k=int(input("enter value of k:... |
s = input("Do you agree? ")
if s.lower() in ["y", "yes"]:
print("Agreed.")
elif s.lower() in ["no", "n"]:
print("Not agreed.")
|
#*************************** CREATING DECRYPTION SHARES ***************************************
def invmodp(a, b):
for d in range(1, b):
r = (d * a) % b
if r == 1:
break
else:
raise ValueError('%d has no inverse mod %d' % (a, b))
return d
if (num ==3):
... |
''''
This is an helper class to the Chilean economic indicator http://mindicador.cl/
using the awesome requests library you can get uf, ivp, dolar, etc.
a simple example:
>> m = Mindicador()
>> m = m.get_uf()
>> uf
{'fecha': '2017-07-23T04:00:00.000Z', 'nombre': 'Unidad de fomento (UF)', 'codigo': 'uf',
'unidad_medid... |
l = input()
print(l, type(l))
s = l.split()
print(s, type(s))
# for i in range(len(s)):
# s[i] = int(s[i])
# print(s)
s = list(map(int, s))
print(s)
def f(x):
return x + 1
# s = [1, 2, 3, 4, 5]
for i in range(len(s)):
s[i] = f(s[i])
s = list(map(f, s))
print(s)
names = ['Zhandos', 'Bekaidar', 'I... |
board = [[' ' for i in range(3)] for j in range(3)]
# board[1][2] = 'X'
# board[0][1] = 'O'
def display():
for i in range(3):
print("+---" * 3 + '+')
for j in range(3):
print(f"| {board[i][j]} ", end='')
print('|')
print("+---" * 3 + '+')
def is_win(player):
win1 = T... |
shop = {}
while True:
role = input("Please, enter your role\n")
if role == 'admin':
while True:
option = int(input("1 to add items\n2 to change role\n"))
if option == 1:
name = input("Please, enter item name\n")
price = int(input("Please, enter it... |
from globals import *
class Star(object):
def __init__(self, mass, radius, pos, vel, color):
self.obj = sphere(pos=pos / DIST_SCALE, radius=radius, color=color)
self.mass = mass
self.vel = vel
self._pos = pos
# Externally use scaled version for physics, use normalized version ... |
import pdb
class people(object) :
def __init__(self,name,age):
self.name = name
self.__age = age
def getName(self):
return self.name
def getAge(self):
return self.__age
class man(people):
def __init__(self,name,age):
pdb.set_trace()
super(man,self).__init__(name,age)
"""
super(man,self)
<super: <clas... |
__author__ = "Danilo S. Carvalho <danilo@jaist.ac.jp>"
from abc import ABCMeta
from abc import abstractmethod
class Annotator(object):
__metaclass__ = ABCMeta
def __init__(self):
"""Formatter constructor
Constructs an annotator object that includes or modify annotations for objects in the da... |
# Pseudocode #
# Take input from the user for number of actors
# Take input from the user for number of roles and attributes
# Create a matrix to store the value of each actor who has roles and attributes
#
# function weighted score with input as the score
# calculate the weight of each score by taking the ... |
while True:
try:
number = int(input("enter a number: "))
print(2/number)
break
except ValueError:
print("Please enter a number")
except ZeroDivisionError:
print("Zero doesn't work")
except Exception as e:
print("some other error: " + re... |
# Programmer: James Aniciete
# Course No.: CSC 157
# Lab No.: 16
# Date: 5/9/2020
from datetime import datetime as DateTime
from datetime import timedelta as TimeDelta
from statistics import mean
from math import ceil
# function to add days to the start date with formatting
def addDays(days) :
start_d... |
def swap(arr,i,j):
arr[i],arr[j]=arr[j],arr[i]
def selection_sort(arr):
for i in range(len(arr)):
minimum=i
for j in range(i+1,len(arr)):
#Select the smallest value
if arr[j] < arr[minimum]:
minimum=j
#Place it the front of ... |
#!/usr/bin/env python
"""A module with the definition of the abstract keystore."""
import abc
class Keystore(metaclass=abc.ABCMeta):
"""A keystore interface."""
@abc.abstractmethod
def Crypter(self, name: str) -> "Crypter":
"""Creates a crypter for the given key to encrypt and decrypt data.
Args:
... |
#!/usr/bin/env python
"""Test utilities for working with time."""
import sys
import time
import dateutil
def Step() -> None:
"""Ensures passage of time.
Some tests need to ensure that some amount of time has passed. However, on
some platforms (Windows in particular) Python has a terribly low system clock
re... |
def print_upper_words(list):
'''Accepts a list, and returns it all capitalized. '''
for word in list:
if word.startswith("e") or word.startswith("E"):
print(word.upper())
print_upper_words(["eggs", "hey", "goodbye", "yo", "yes", "Eeeeeeeh"])
def print_e_words(list):
'''Accepts a list,... |
"""In a small town the population is p0 = 1000 at the beginning of a year.
The population regularly increases by 2 percent per year and moreover 50 new
inhabitants per year come to live in the town. How many years does the town
need to see its population greater or equal to p = 1200 inhabitants?"""
def nb_year(p0, per... |
class Solution:
def lemonadeChange(self, bills: [int]) -> bool:
fives, tens, twenties = 0,0,0
print(bills)
for bill in bills:
if bill == 5:
fives+=1
elif bill == 10:
tens +=1
if fives>=1:
fives -=1
else:
return ... |
class Solution():
def reverse(self, x: int) -> int:
neg = 0
if (x<0):
x *= -1
neg = 1
res = 0
while(x>0):
temp = x%10
res = res*10+temp
x = int(x/10)
if(neg):
res*= -1
return res
t = Solution()
print (t.reverse(-123)) |
from collections import OrderedDict
def odd_numbers():
lst = [1, 5, 6, 12, 19, 7, 8, 44, 27]
total = 0
for i in lst:
if i % 2 == 1:
total += i
print(total)
def sum_elements():
lst = [1, 5, 6, 12, 19, 7, 8, 44, 27]
total = sum(lst)
print(total)
def reverse_string(word... |
import re
# checker with out 'cid'
passport_fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
valid_passport = 0
# file read
file_name = "input.txt"
f = open(file_name)
# get file content
file_lines = f.readlines()
file_content = ""
i = 0
for line in file_lines:
if line == '\n':
file_content = ... |
import math
import numbers
class Vec3(object):
def __init__(self, e0, e1, e2):
self.e = (e0, e1, e2)
@property
def x(self):
return self.e[0]
@property
def y(self):
return self.e[1]
@property
def z(self):
return self.e[2]
@property
def r(self):
... |
def getorder(a):
from datetime import date
today = date.today()
products=[]
amounts=[]
prices=[]
product = input("enter which food u want ")
amount = int(input("enter amount of ur product"))
money=input("if u pay in GEL write GEL and if you pay with USD write USD")
m... |
import functools
class Query:
"""Queries python objects for their values.
Args:
*args: The series of `queryable` functions
Typical usage would pass in `queryable` functions in order to enable
the class to perform actions on the passed in python object. For example,
if three functions are... |
#!/usr/bin/python
#Filename:using_dict.py
#'ab' is short for 'a'ddress'b'ook
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']
#Adding a key/value pair
ab['Guido... |
#!/usr/bin/python
#coding:UTF-8
#Filename:time.py
import time
import datetime
print time.clock()
print time.time()
print time.ctime()
print time.strftime('%Y-%m-%d %H:%M:%S')
print time.strftime('%Y%m%d')
print time.strftime('%Y')
##day dec one day
yesterday = datetime.date.today() - datetime.timedelta(days=1)
print ... |
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import os
def child():
print('Hello from child',os.getpid())
def parent():
for i in range(3):
print(i)
newpid = os.fork()
if newpid == 0:
child()
else:
print('Hello from parent',os.getpid(),newpid)
parent()
|
#python program to check armstrong number
# i=int(input("Enter the number to check for armstrong"))
# orig=i
# sum=0
# while(i>0):
# sum=sum+(i%10)*(i%10)*(i%10)
# i=i//10
# if orig==sum:
# print("number is armstrong")
# else:
# print("number is not armstrong")
#second way
# n=int(input("enter ... |
def longest_common_prefix(strs):
def is_common_prefix(strs, length):
str1 = strs[0][:length]
for i in range(1, len(strs)):
if not strs[i].startswith(str1):
return False
return True
if not strs:
return ""
min_len = len(min(strs, key=len))... |
"""Using the random module, generates two positive one-digit numbers.
Displays a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”.
Uses random to generate +, -, or * as the operators.
Conducts error-checking on the answer and notifies the user whether the answer is correct or not.
At... |
# # a='qwert123'
# # s=('q','2','4')
# # d=['w','1','2','5']
# # f={'y','e','q','3'}
# # g={'name':'小柒','are':'女','log':'12'}
# # print('q'in a)
# # print('q'in d)
# # print('log'in g)
# #
# # money=77
# #
# # if(money<=100):
# # print('找富婆')
# # elif(money<200):
# # print('何智彬鸭鸭包邮')
# # elif (money<1000):
# # ... |
def domain_name(url):
url = url.replace('http://', '')
url = url.replace('https://', '')
url = url.replace('www.', '')
url = url.split('.')
return url[0]
print(domain_name("http://google.com"))
print(domain_name("http://google.co.jp"))
print(domain_name("www.xakep.ru"))
print(domain_name("https://... |
while True:
try:
n = input("Please input integer: ")
n = int(n)
break
except ValueError:
print("Input not integer, please try again.")
print("Correct input") # until user correct input, then run out of the loop
|
import random
import string
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1,
'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1,
's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
path = '/Users/Xeus/my-project/MIT-Pytho... |
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
month = 0
while month < 12:
month += 1
minimum_paid = monthlyPaymentRate * balance
unpaid_b = balance - minimum_paid
interest = (annualInterestRate / 12) * unpaid_b
balance = unpaid_b + interest
balance = round(balance, 2)
print... |
import datetime
class Person(object):
def __init__(self, name):
"""crete person called name"""
self.name = name
self.birthday = None
self.lastname = name.split(' ')[-1]
def get_lastname(self):
"""return self's lastname"""
return self.lastname
def set_birth... |
import random
class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, new_age):
self.age = new_age
def set_name(self, new_name):
self... |
animals = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
# print(animals)
def how_many(aDict):
temp = []
sub_list = []
for i in aDict:
temp.append(aDict[i])
for j in temp:
sub_list.append(j)
an... |
x = int(input('Please think of a number between 0 and 100!'))
epsilon = 0
guess_range = 0
high = x
low =
answer = (high + low) / 2
print("Is your secret number 50?")
print("Enter 'h' to indicate the guess is too high.", end=' ')
print("Enter 'l' to indicate the guess is too low.", end=' ')
print("Enter 'c' to indicate... |
print('Please think of a number between 0 and 100!')
num_guesses = 0
low = 0
high = 100
answer = int((high + low) / 2.0)
checking = ''
while checking != 'c':
answer = int((high + low) / 2.0)
print("Is your secret number ", answer, '?')
print("Enter 'h' to indicate the guess is too high.", end=' ')
prin... |
def fib_efficient(n, d):
"""
n = number of fibonacci that want to calculate
d = base case dictionanries
"""
if n in d:
return d[n]
else:
answer = fib_efficient(n-1, d) + fib_efficient(n-2, d)
d[n] = answer
return answer
# base case
d = {1: 1, 2: 2} # fib(1) = 1... |
# we can iterate over string using for-loop
s = 'Hello World'
for char in s:
print(char)
print('-------------------------')
# or we can iterate over range of length
for i in range(len(s)):
print(s[i])
|
def hasPalindromePermutation(input):
""" Check if any of a string's permutations are a palindrome
e.g.
Input: rraceca
Output: true ('racecar' is a palindrome and permutation of input)
Runtime complexity O(N)
Space complexity O(N) """
asciiChars = [0 for i in range(128)]
for c i... |
#Google
'''
Given an array a that contains only numbers in the range from 1 to a.length,
find the first duplicate number for which the second occurrence has the
minimal index. In other words, if there are more than one dupplicated numbers,
return the number for which the second occurrence has a smaller index than
... |
with open("day09") as file:
stream = file.readline()
garbage = False
ignorenext = False
grp = 0
grp_depth = 0
garbage_count = 0
for char in stream:
if garbage == True and char != "!" and char != ">" and not ignorenext:
garbage_count += 1
if ignorenext:
ignorenext = False
... |
def findItinerary(tickets):
from collections import defaultdict
graph=defaultdict(list)
# 그래프를 역순으로 구성해서 pop사용
for a,b in sorted(tickets,reverse=True):
graph[a].append(b)
visit=[]
def dfs(a):
# 마지막값(역순으로해서 pop)을 어휘 순으로 방문
while graph[a]:
dfs(grap... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(self,l1: ListNode, l2: ListNode) -> ListNode:
if (not l1) or (l2 and l1.val>l2.val):
l1,l2=l2,l1
if l1:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
l... |
def numIslands(matrix):
def dfs(i,j):
# 육지가 아니면 종료
if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]) or matrix[i][j] != "1":
return
matrix[i][j]=0
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j+1)
dfs(i,j-1)
cnt=0
for i in range(... |
# class Solution:
def evalRPN(tokens):
num=[]
cal=['-','+','*','/']
for i in tokens:
if i not in cal:
num.append(int(i))
else:
num1=num.pop()
num2=num.pop()
print(num2,num1,i)
if i=='+':
num.append(num2+n... |
"""함수의 적분
사다리꼴 방법을 이용한 함수의 적분량 계산
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import trapezoid
h = 0.01
min_x = 1
max_x = 5
def f(x):
return 3 * x ** 2 + 2 * x + 6
def int_f(func, x_min, x_max, h):
output = 0
x = np.arange(x_min, x_max, h)
for idx in range(len(x) -... |
"""개미집단 최적화
"""
import matplotlib.pyplot as plt
import numpy as np
area = np.ones([20, 20]) # 지역 생성
start = (1, 1) # 개미 출발지점
goal = (19, 14) # 도착해야 하는 지점
path_count = 40 # 경로를 만들 개미 수
path_max_len = 20 * 20 # 최대 경로 길이
pheromone = 1.0 # 페로몬 가산치
volatility = 0.3 # 스탭 당 페로몬 휘발율
def get_neighbors(x, y):
"""x... |
'''
Character-Level LSTM in PyTorch
In this code, I'll construct a character-level LSTM with PyTorch. The network will train
character by character on some text, then generate new text character by character.
This model will be able to generate new text based on the text from any provided book!
This network is based ... |
print()
print("Project: Linear Regression")
print()
print("Reggie is a mad scientist who has been hired by the local fast food joint to")
print("build their newest ball pit in the play area. As such, he is working on")
print("researching the bounciness of different balls to optimize the hole. Reggie is")
print("running... |
#!/usr/bin/env python
"""
Demonstrates the cleaning and normalization of data.
The Indian Diabetes dataset has 768 rows.
However, many of them have zeros as values, which are wrong values, e.g.
in the case of BloodPressure. Nobody has such blood pressure.
ToDo: Instead of dropout these records, replace the
zeros by th... |
#!/usr/local/bin/python3
#
# choose_team.py : Choose a team of maximum skill under a fixed budget
#
# Code by: [PLEASE PUT YOUR NAMES AND USER IDS HERE]
#
# Based on skeleton code by D. Crandall, September 2019
#
import sys
def load_people(filename):
people={}
with open(filename, "r") as file:
for line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.