text stringlengths 37 1.41M |
|---|
"""Scans a given path (folder) for .wav files recursively and copys all of
them into a new folder.
"""
from pathlib import Path
import shutil
import click
from wavlength import get_files
@click.command()
@click.option('--scan_folder', default='.', help='The folder to scan.')
@click.option('--copy_folder',... |
def somethingElse():
pass
class Base:
"""This is the Base class to rule all classes"""
someVar = "Some shared value"
def __init__(self,id='',desc='No Description'):
print("Base class init fx")
self.id = id
self.address = ''
self.description = desc
self.data = di... |
#This is Patrick's text base RPG adventure.
class Player:
""" You are the player """
def __init__(self, name, prof, maxhp, level, attack, defense = 5):
self.name = name
self.life = 1
self.attack = attack
self.defense = defense
self.hp = 100
self.xp = 0
def l... |
# Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
def difference_of_squares(n):
# if n % 2 == 1:
# median = (n + 1) / 2
# num_pairs = (n - 1) / 2
# else:
# median = 0
# num_pairs = n / 2
#
# square_of_sum = (n... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 14 20:10:31 2017
@author: Usuryjskij
"""
import pygame
from pygame.locals import*
GREEN = ( 0, 204, 0)
cant_place_ship = [[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10]
class Ship(object):
... |
import string
from typing import List
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
# approach 1: replace each character with uppercase original alphabet
# 'hello' -> 'AGBBO'
# check whether the list is in sorted order
# O(NK) time, O(NK) space
... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# O(n) time, O(1) space
if not l1:
return l2
if not l2:
return l1
... |
from typing import List
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
# one-pass through nums and record the sign of the previous difference
# also record the last "transition number"
# O(n) time, O(1) memory
if len(nums) == 1:
return len(nums)
... |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
# traverse the tree using dfs
# for node i:
# maxsum = max(maxsum, left + val + right... |
class Solution:
def halvesAreAlike(self, s: str) -> bool:
# O(n) time, O(n) space
isVowel = [1 if c in ['a', 'e', 'i', 'o', 'u'] else 0 for c in s.lower()]
return sum(isVowel[:len(s)//2]) == sum(isVowel[len(s)//2:])
sol = Solution()
print(sol.halvesAreAlike("Book"))
print(sol.halvesAreAlike... |
import heapq
from typing import List
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
# BFS approach
# at each building, take all viable options in the queue, move forward using bricks or ladders
# O(2**H) time
# use bricks ... |
from typing import List
from collections import Counter
from itertools import accumulate
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
# record the brick boundaries of each row in a counter
# find the boundary that has max count
# O(N) time, O(N) space, N is the numb... |
from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
return (len(nums)+1) * (len(nums)) // 2 - sum(nums)
sol = Solution()
print(sol.missingNumber([0]))
print(sol.missingNumber([0, 1]))
print(sol.missingNumber([0, 3, 1]))
|
class Solution:
def removePalindromeSub(self, s: str) -> int:
# insight: answer is at most 2
if not s:
return 0
elif s == s[::-1]:
return 1
else:
return 2
sol = Solution()
print(sol.removePalindromeSub(""))
print(sol.removePalindromeSub("ababa"))
... |
# locals() 지역 이름공간
global_var = 77
def myfunc():
global global_var
global_var += 1
print(global_var)
myfunc()
var = 77
def func():
global var
var = 100
print(locals())
func()
print(var)
def local_func():
var = 100
print(locals())
local_func() |
# Duplicate number in an array
# Approach 1 - Sum of numbers - Time complexity= O(n) space complexity= O(1)
# If array contains consecutive numbers
num=list(map(int, input().split()))
sum=0
for i in num:
sum=sum+i
print(int(sum-(((len(num)-1)*(len(num)))/2)))
# Duplicate number in an array
# Approach 2 -... |
# Check Rotations
'''
1. Create a temp string and store concatenation of str1 to
str1 in temp.
temp = str1.str1
2. If str2 is a substring of temp then str1 and str2 are
rotations of each other.
'''
st1=str(input())
st2=str(input())
st1=st1+st1
n=st1.count(st2)
if(n>0):
... |
# Check if All Digits
st1 = str(input())
flag = 0
for i in st1:
if(i.isdigit()==True):
flag+=1
if(flag==len(st1)):
print("All Digits")
else:
print("Not All Digits") |
# https://www.geeksforgeeks.org/find-one-extra-character-string/
# Find one extra character in a string
st1=str(input())
st2=str(input())
count=0
for i in st2:
if(i not in st1):
print(i)
else:
n1=str.count(st1,i)
n2=str.count(st2,i)
if(n2>n1):
print(i)
... |
# Remove Punctuations
# https://www.geeksforgeeks.org/removing-punctuations-given-string/
st=str(input())
for i in '''!"#$%&'()*+,-./:;?@[\]^_`{|}~<>''':
if(i in st):
st=st.replace(i,'')
print(st)
|
file = open("advent_day2_input.txt", "r")
f = file.readlines()
for line1 in f:
for line2 in f:
distance = sum([1 for x, y in zip(line1, line2) if x.lower() != y.lower()])
if distance == 1:
print "line1: " + line1 + " , line2: " + line2
#for line in f:
# for char in line:
# ... |
import re
from collections import Counter
def splits(text, start=0, L=10):
"Return a list of all (first, rest) pairs; start <= len(first) <= L."
return [(text[:i], text[i:])
for i in range(start, min(len(text), L)+1)]
def product(nums):
"Multiply the numbers together. (Like `sum`, but with ... |
class Heap:
def __init__(self):
self.values = []
self.size = 0
def insert(self, x):
self.values.append(x)
self.size += 1
self._sift_up(self.size - 1)
def _sift_up(self, i):
while i != 0 and self.values[i] < self.values[(i - 1) // 2]:
self.values[... |
def manhattan_distance(point_a: tuple, point_b: tuple) -> bool:
"""
:param point_a:
:param point_b:
:return:
"""
return True if (abs(point_b[0] - point_a[0]) + abs(point_b[1] - point_a[1])) % 2 == 0 else False
if __name__ == '__main__':
# Вводятся координаты начальной и целевой клеток шах... |
import cv2
import numpy as np
image = cv2.imread('../images/input.jpg')
## 1. here display translation(圖像位移)!!!!
# Store height and width of the image
height, width = image.shape[:2]
quarter_height, quarter_width = height/4, width/4
# T = | 1 0 Tx |
# | 0 1 Ty | 是一個二維陣列
# 寬度位移Tx距離,高度位移Ty距離
# T is our tran... |
def fizz_buzz(arg):
"""a function that returns FizzBuzz, Fizz or Buzz for multiples of both 5 and 3, 3 or 5 respectively"""
if isinstance(arg, int):
if arg % 5 == 0 and arg % 3 == 0:
return "FizzBuzz"
elif arg % 3 == 0:
return "Fizz"
elif arg % 5 == 0:
... |
fizz = []
buzz = []
fizzbuzz = []
for x in range(1, 101):
n = ''
if x % 3 == 0:
n += 'fizz'
fizz.append(n)
if x % 5 == 0 and x % 3 != 0:
buzz.append('buzz')
if x % 5 == 0:
n += 'buzz'
if n == 'fizzbuzz':
fizzbuzz.append('fizzbuzz')
if x % 5 !... |
#Leetcode N932
# For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
# For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
# Given N, return any beautiful array A. (It is guaranteed that one exists.)
class Solution(object):
def bea... |
import datetime
import time
def main():
date=datetime.datetime.now()
print date.year
print date.month
print date.day
print date.hour
print date.minute
print date.second
print "{}_{}_{}__{}_{}_{}".format(date.year,date.month,date.day,date.hour,date.minute,date.second)
main()
|
import random
def start_game():
the_table = database()
game_table = database()
index = 0
difficult_level = 0
while index < 1:
difficult = input("Válassz nehézséget (1-3): ")
if difficult in ['1', '2', '3']:
difficult_level = difficult
index += 1
else... |
import random
def partition(Arr,p,r):
x = Arr[r]
i = p - 1
for j in range(p,r-1):
if Arr[j] <= x:
i += 1
t = Arr[i]
Arr[i] = Arr[j]
Arr[j] = t
t = Arr[i+1]
Arr[i+1] = Arr[r]
Arr[r] = t
return i+1
def randomizedPartition(Arr,p,r):
i = random.randint(p,r)
t = Arr[r]... |
import insertion
import mergesort
import linearsearch
import binarysearch
Arr1 = [-3,5,8,7,1,-2,4]
Arr2 = [5,8,-6,12,3,7,1,9,10]
Arr3 = [44,31,-61,12,3,71,1,19,56,-25]
print ("Unsorted array :")
print (Arr1)
print ("Unsorted array :")
print (Arr2)
insertion.insertionSort(Arr1)
print ("Sorted array :")
print (Arr1)... |
import vertex_example
time = 0
class Graph:
def __init__(self,g = None,s = 0):
self.graph = g
self.size = s
def addVertexToGraph(self,vertex):
self.graph.append(vertex)
self.size += 1
def addVertexAdjacent(self,vertexNum,vertex):
(self.graph[vertexNum]).adjace... |
import datetime
class Timer():
def __init__(self):
self.start_time = None
self.end_time = None
def start(self):
self.start_time = datetime.datetime.now()
def stop(self):
self.end_time = datetime.datetime.now()
print("Time taken: %s" % (self.end_time - self.start_... |
# Упражнение №4. Задачи посложнее.
# 1. Переставьте соседние элементы в списке. Задача решается в три строки.
A=[1,2,3,4,5]
for i in range(len(A)-1):
A.insert(i,A.pop(A[i]))
print(A)
|
# Упражнение №12
# В списке — нечетное число элементов, при этом все элементы различны. Найдите медиану списка: элемент,
# который стоял бы ровно посередине списка, если список отсортировать.
# При решении этой задачи нельзя модифицировать данный список (в том числе и сортировать его),
# использовать вспомог... |
# Упражнение №9
# Вывести список в следующем порядке: первое число, последнее, второе, предпоследнее и так далее все числа.
#Ввод Вывод
#1 2 3 4 5 1 5 2 4 3
#Ввод Вывод
#1 2 3 4 1 4 2 3
A=[1,2,3,4,5]
B=[]
while len(A)>0:
B.append(A.pop(0)) # вытаскиваем из списка первый элемент и добавляем в B
if len(A)>0:... |
#to optimize the algorthim i have used fractions
#import fractions funtion
import fractions
#define a function with ar argument n
def smallestdivisble(n):
#set the intial value to 1
number = 1
#set the range
for i in range(1,n+1):
#mutiply the i value with cureent number value and divide it wilt... |
#Copy lines 2 to 5 first and paste them to console.
import pandas as pd
cars = pd.read_csv('cars.csv')
print("First 5 rows:")
cars.loc[[0,1,2,3,4]]
#Now, copy lines 7 and 8 then paste them to console.
print("Last 5 rows:")
cars.loc[[27,28,29,30,31]]
#Copy and paste the lines of code below to console in order to... |
from zipfile import ZipFile
import os
import wget
def downloader_file(download_link, destino): #, tipo_arquivo, nome):
"""
Função para fazer download de um arquivo a partir
de uma única URL. O download é feito para a pasta
/arquivos/.
"""
file = wget.download(download_link,out=destino)
... |
def read_file_info(file_name: str):
number_of_chars = 0
number_of_words = 0
number_of_lines = 0
with open(file_name, 'r') as file:
for lines in file:
words = lines.split()
number_of_lines += 1
number_of_words += len(words)
number_of_chars += len(l... |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... |
# part 1
def countdown(num):
result = []
for x in range(num, -1, -1):
result.append(x)
return result
print(countdown(12))
# part 2
def firstsecond(x):
print(x[0])
return(x[1])
x = firstsecond([1,2])
print(x)
# part 3
def first_plus_length(arr):
return arr[0] + len(arr)
total = first_p... |
# -*-encoding:utf-8-*-
import os
KEYWORD_FILE_PATH = "./keyword.txt"
class Keyword:
def __init__(self):
if not os.path.exists(KEYWORD_FILE_PATH):
with open(KEYWORD_FILE_PATH, "w")as fw:
fw.write("# 关键词格式如下,由#分隔\n")
fw.write("关键词1#关键词2#关键词n#") # 每个关键词后面带#,这是标准格... |
for n in range(1,10):
for m in range(1,10):
print("%d*%d = %2d"%(m, n, n*m), end="\t")
print("\n")
|
# # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# class Solution:
# def maxDepth(self, root: TreeNode) -> int:
# if root is None:
# return 0
# stack = [(1, root)]
# ... |
'''message = "Hello , How are you?"
print(message)
'''
simple_math_string = f"2+3 is equal to {2+3} "
print(simple_math_string)
s = "Hi"
print(s[1])
print(len(s))
print(s + ' there')
|
# A list is a collection which is ordered and changeable. Allows duplicate members
# Create a list
numbers = [1, 2, 3, 4, 5]
fruits = ['Apples', 'Oranges', 'Grapes', 'Pears']
# Use a constructor
# numbers2 = list((1, 2, 3, 4, 5))
# print(numbers, numbers2)
# Get a value
print(fruits[1])
# Get length
... |
import numpy as np
import math
class Spherical(object):
'''
(x - a)^2 + (y - b)^2 = r^2
so circles have a centerpoint (a,b) and a radius (r)
'''
def __init__(self, focal_length, depth, height):
self.height = height
self.r = abs(self.focal_length_to_radius(focal_length))
... |
import random
def repeat():
print("To play again, type PLAY")
response = input("> ")
if response == "PLAY":
game()
def game():
rand = random.randint(1, 10)
guesses = 0
guessed = 0;
print("Welcome to the Number Guessing Game.")
while guessed != rand:
if guesses == 5:
print("You ra... |
#!/usr/bin/env python
#
# ===============================================================
# ADVENT OF CODE
# ===============================================================
# DAY 12 FERRY LOGO
#
# A: Manhattan distance between start and end points
# B:
# ========================================... |
courses = [ 'bch310' , 'bch311' , 'bch312' , 'bch313' , 'bch315' , 'pbb313' , 'chm311' , 'ced300' ]
grades = {
'A':5,
'B':4,
'C':3,
'D':2,
'F':0
}
courses_credits = {
'bch310' : 5,
'bch311' : 2,
'bch312' : 4,
'bch313' : 4,
'bch315' : 2,
'pbb313': 3,
'chm311': 4,
... |
n = int(input())
res = []
for _ in range(n):
i = int(input())
if not res or i != res[-1]:
res.append(i)
for i in res:
print(i)
# METHOD 2
#n = int(input())
#res = []
#
#for _ in range(n):
# i = int(input())
# if i not in res:
# res.append(i)
#
#for i in res:
# print(i)
# METHOD 3... |
def is_parent(dic, child, parent):
if child == parent:
return True
for e in dic[child]:
if is_parent(dic, e, parent):
return True
return False
n = int(input())
parents = {}
for _ in range(n):
a = input().split()
parents[a[0]] = [] if len(a) == 1 else a[2:]
m = int(inp... |
''' Combines sentences from wikipedia articles '''
from bs4 import BeautifulSoup
from nltk import pos_tag, word_tokenize
import re
import requests
import sys
def get_page(page=None):
''' load and parse a wikipedia page '''
if page and page != 'http://en.wikipedia.org/wiki/':
r = requests.get(page)
... |
#coding=utf-8
'''
下面已a = 10 ,b = 20 为例进行计算
运算符 描述 实例
+ 加 两个对象相加a+b 输出结果为30
- 减 得到负数或是减去一个数 a-b 输出结果为-10
* 乘 两个数相乘或是返回一个被重复若干次的字符窜 a*b输出结果为200
/ 除 X除以Y b/a 输出结果为2
// 取整除 返回商的整数部分 9//2 输出结果为4,9.0//2.0 输出结果为4.0
% 取余 返回除法的余数 b%a 输出结果为0
** 幂... |
#coding=utf-8
#三个条件,皮肤白/有钱/美
color = int(input('请问你的皮肤白吗?1.白 2.不白'))
rich = int(input('请问你的财富总额有多少?'))
beutiful = int(input('请问你漂亮吗?1.是 2.不是'))
if color==1 and rich>100000 and beutiful==1:
print('你好白富美....')
elif color==1 and rich<100000 and beutiful==1:
print('你好美女')
elif color==2 and rich>100000 and beutifu... |
#-----------------------------------------------------------
# Implementation of classic arcade game Pong
#
# Additional Functions for abit of fun:
# - The players can add there names
# - A single player option which sincs both paddles with
# the Up and Down arrows
#--------------------------------------------------... |
'''
Quicksort is a quick and efficient sorting algorithm.
It recursively sorts by selecting a pivot and sending all elements smaller than the pivot to the left of it, and the elements larger than it to the right.
The array is now divided into sub-arrays separated by the pivot picked. The process repeats itself recurs... |
"""
A Singly-Linked List is a sequence of objects that point to the next item in
the list but have no back references to previous items in the list.
"""
class ListElement:
def __init__(self, data):
self.next_item = None
self.data = data
def append(self, data):
self.last().next_item = ... |
import tensorflow as tf
from tensorflow import keras
from nn import activations
# %%
class NeuralNet(object):
"""
A neural network model
Attributes
----------
trainable_params : itarable
contains all trainable parameters.
layers : iterable
ordered collection of network layers... |
import time
# 1.使用全局函数来装饰类方法
# 2.使用类方法来装饰类方法
# 3.使用类内置方法来装饰实例方法
# def a_(fun):
# class A(object):
# def __init__(self):
# self.a_ = 100
# @a_ #使用全局函数装饰
# def func(self, num):
# def b_(fun):
# @b_ #使用类内方法装饰
# def func1(self, num):
# c = A()
# c_ = c.func(100)
# print(c_) #200
# ... |
import sys
import re
import numpy as np
comparisons = 0
FIRST = 0
LAST = 1
MIDDLE = 2
def swap( arr, a, b ):
keep = arr[ a ]
arr[ a ] = arr[ b ]
arr[ b ] = keep
return
def find_pivot( el ):
if len( el ) % 2 == 0:
middle_index = int( len( el ) / 2 - 1 )
else:
middle_index = l... |
def CompareLists(headA, headB):
while (headA != None and headB !=None):
if (headA.data != headB.data):
return 0
headA = headA.next
headB = headB.next
if (headA == None and headB == None):
return 1
else:
return 0 |
#!/bin/python
def print_list(ar):
print(' '.join(map(str, ar)))
def insertionSort(ar):
if len(ar) == 1:
print_list(ar)
return(ar)
else:
for j in range(1, len(ar)):
for i in reversed(range(j)):
if ar[i + 1] < ar[i]:
ar[i], ar[i + 1] = ar[i... |
N = int(raw_input())
X = [int(x) for x in raw_input().split(" ")]
F = [int(x) for x in raw_input().split(" ")]
def unravel_input(X, F, N):
S = []
for i in range(0,N):
temp = [X[i]]*F[i]
S = S + temp
return S
def quartile(X):
N = len(X)
middle = N/2
if(len(X) % 2 != 0):
middle = middle + 1
A = sorted(X... |
# program to get all the numerical set in a string
# helper_function
def is_alpha(a):
a = a.lower()
if a >= 'a' and a <= "z":
return True
return False
def get_numerical_set(str):
str = str.replace(" ", "")
numerical_num = ""
for i in range(0, len(str)):
if no... |
# program to find second largest number in the array
arr=[34,213,45,213,63]
def find_max(arr):
max = 0
index = None
for i in range(0, len(arr)):
if(max < arr[i]):
index = i
max = arr[i]
return index
# print(find_max(arr))
def second_max(arr):
arr... |
# program to find max number in an array
# using buidin-function
def max_num(arr):
return max(arr)
print(max_num([3,2,4,6]))
# using logic
def max_num2(arr):
maxnum=0
for i in range(0,len(arr)):
if arr[i]>maxnum:
maxnum=arr[i]
return maxnum
print(max_num2([4... |
# single linked list implementaion in python and also
# implementaion of helper function used in linked list
# Creating Node
class node:
def __init__(self, data):
self.data = data
self.next = None
# Creating linkedList
class linkedList:
def __init__(self):
self.he... |
# program to find the median of an array
# helper function to merge two arrays
def merge_arrays(arr1, arr2):
arr3 = arr1+arr2
return sorted(arr3)
arr1 = [5, 4, 3, 2, 1]
arr2 = [11, 10, 9, 8, 7]
def find_median(arr1, arr2):
arr3 = merge_arrays(arr1, arr2)
array_len = len(arr3)-1
... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
bubble sort implementation, basic concepts:
promote the minimum item one by one, from end to beginning.
"""
def BubbleSort(alist):
for i in range(0, len(alist)):
for j in range(len(alist)-1, i, -1):
if alist[j] < alist[j-1]:
alist[j], alist[j-1] = alist[j-1], ... |
import sqlite3
import json
DB_FILENAME = "Database/Data/database.db"
class SqlInterface:
def __init__(self):
self.connection = sqlite3.connect(DB_FILENAME)
self.connection.execute("""
CREATE TABLE IF NOT EXISTS user (
username TEXT,
password TEXT,
emai... |
#%% #creates separate cell to execute
from keras.datasets import mnist #import MNIST dataset
from keras.models import Sequential #import the type of model
from keras.layers.core import Dense, Dropout, Activation, Flatten #import layers
from keras.layers.convolutional import Convolution2D, MaxPooling2D #import... |
"""
[][][][][][x][][]
K
N other players numbered 1 to N. Chef can choose who to play against.
so player i is found at positions l*p[i] where l is an integer.
Does it jump over positions?
if player moves pawn to square with Chef's pawn chef's pawn is
captured and loses the game.
Idea
Find the shortest distan... |
def generate_cake(firstColour, secondColour, width, breadth):
resArr = [[0 for j in range(width)] for i in range(breadth)]
for i in range(breadth):
for j in range(width):
if (i+j)%2 == 0:
resArr[i][j] = firstColour
else:
resArr[i][j] = secondColou... |
fDic ={}
fDic[1]=1
fDic[2]=2
fDic[3]=4
fDic[4]=8
def f(n):
if n in fDic:
return fDic[n]
else:
fDic[n]= f(n-1)+f(n-2)+f(n-3)+f(n-4)
return fDic[n]
print f(50) |
#!/bin/python
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
sys.setrecursionlimit(1000000)
def palindrome(A, a, b, c, d):
pal = xorsum[a][b] ^ xorsum[c][d] ^ xorsum[a][d] ^ xorsum[c][b]
nzero = nzeroes[c][d] - nzeroes[a][d] - nzeroes[c][b] + nzeroes[a][b]
if (pal & (pal ... |
"""
Link to (question)[https://www.codechef.com/SEPT20B/problems/CRDGAME2]
The key idea here is that the maximum never changes the pile it belongs to
while every other number will change the pile it belongs to and reduce by 1
So we can focus on the number of maximum values.
if the number of maximum values is odd, it d... |
#!/bin/python
import sys
from math import ceil
def lowestTriangle(base, area):
# Complete this function
return int(ceil(area / float(base) * 2))
base, area = raw_input().strip().split(' ')
base, area = [int(base), int(area)]
height = lowestTriangle(base, area)
print(height)
|
""" Project Euler 152"""
import fractions
f = [fractions.Fraction(1,i*i) for i in xrange(2,101)]
f = [1.0/float(i*i) for i in xrange(2,101)]
#print f
#You are given N and D. result should be the number of ways of writing 1/D as a sum of square fractions less than N+1
#use a backtracking algorithm
Solution = []
def ... |
def atm(x , y):
'''This function take tow argument balance and requested money '''
if x > y:
hundre = y /100
print "give100\n" * hundre
gived = hundre*100
rest1 = y - gived
fifteen = rest1 /50
print "give50\n" * fifteen
gived2 = fifteen * 50
rest2 = y - (gived + gived2 )
ten = rest2 / 10
print "... |
# 문제16 : 로꾸거
# 문장이 입력되면 거꾸로 출력하는 프로그램을 만들어 봅시다.
# >> 입력
# 거꾸로
# >> 출력
# 로꾸거
data = input("단어를 입력 : ")
print(data[::-1]) |
# 문제14 : 3의 배수 인가요?
# 영희는 친구와 게임을 하고 있습니다. 서로 돌아가며 랜덤으로 숫자를 하나 말하고 그게 3의 배수이면 박수를 치고 아니면 그 숫자를 그대로 말하는 게임입니다.
# 입력으로 랜덤한 숫자 n이 주어집니다.
# 만약 그 수가 **3의 배수라면 '짝'이라는 글자를, 3의 배수가 아니라면 n을 그대로 출력**해 주세요.
# >> 입력
# 3
# 짝
# 2
# 2
data = int(input("숫자를 입력: "))
if data % 3 == 0:
print("짝")
else:
print(data) |
#!/usr/bin/env python3
def get_best_savings_rate(starting_annual_salary, r=0.04, total_cost=1000000, portion_down_payment=0.25, semi_annual_raise=0.07):
months = 36
threshold = 100
amount_to_save = total_cost*portion_down_payment
savings = 0
num_guesses = 0
low = 0
high = 10000
guess = ... |
# Goal:To get all the city name in website lianjia
# Purpose: practise beautifulsoup
# Sophia 20190914
# filename: citys.py
# coding: utf-8
import sys
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.lianjia.com"
# get html page
html = urlopen(url).read()
# get Beau... |
#title-factorial of a no
#Nilay Pedram
#M-45
def factorial(n): #defining the fun
f=1
if n<0: #if-elif statement
print('enter positive no.')
elif n==0 or n==1:
print('1')
else:
while n>1: ... |
# 寫一個打印菜單的函數
def show_menu():
print('+--------------------------------+')
print('| 1) 添加學生信息 |')
print('| 2) 查看所有學生信息 |')
print('| 3) 修改學生的成績 |')
print('| 4) 刪除學生信息 |')
print('| 5) 按成績從高至低打印學生信息 |')
print('| 6) 按成績從低至高打印學生信息 |')
p... |
list_elementos=['piedra','papel','tijeras','lagarto','holk']
while(True):
juegos= int(input("Ingrese la cantidad de veces a jugar:"))
for i in list(range(0, juegos)):
print("\n","Caso #",i+1,":")
Caso= str(input("Ingrese respuestas de los jugadores:")).lower().replace("roca","piedra")
if len(Caso.split... |
#!/usr/bin/python2.7
import pygame
from pygame.locals import *
def main():
#Initialize Screen
pygame.init()
screen = pygame.display.set_mode((150,150))
pygame.display.set_caption("Basic Pygame Program")
#Fill Background
background = pygame.Surface(screen.get_size())
background = background.convert()
backg... |
def recurv(n):
if n<=1:
return n
else:
return n + recurv(n-1)
if num < 0:
print("print +ve number")
else:
print("sum is",recurv(num))
|
import time
# my function of is_prime
def is_prime(n):
if n == 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3,int(n**0.5)+1):
if n % i == 0:
return False
return True
t1 = time.clock()
for n in range(1,150000):
is_prime(n)
t2 = time.clock()
... |
# -*- coding: utf-8 -*-
import sys
"""
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence,
and characterized by the fact that every number after the first two is the sum of the two preceding ones
https://en.wikipedia.org/wiki/Fibonacci_number
"""
de... |
#This script is used for try/except block
def divideBy(num):
try:
return (42/num)
except ZeroDivisionError:
print("you are trying to divide a number by zero")
print(divideBy(2))
print(divideBy(12))
print(divideBy(0))
print(divideBy(1))
|
def divideBy(num):
return (42/num)
try:
print(divideBy(2))
print(divideBy(12))
print(divideBy(0))
print(divideBy(1))
except ZeroDivisionError:
print('You are trying to divide by ZERO which is not right')
|
# This is use For loop
##for i in range(10): # this will start from 0 until 9 and excluding 10
## print(i)
##
##for i in range(1,10): # this will start from 1 until 9
## print(i)
##for i in range(1,10,2): #This will pring from 1-9 with jump of 2 numbers
## print(i)
for i in range(20,10,-2): #This will pri... |
# Rakin Uddin
import unittest
from heaps import *
class TestHeapMethods(unittest.TestCase):
def test_init(self):
# Check if the heap is initialized properly
test_heap = Heap([1, 2, 3, 4])
self.assertEqual(test_heap._heap, [4, 3, 2, 1])
# Heap is empty when initializing ... |
# lesson 03, chapt 2, challenge 4
'''
Write a Car Salesman program where the user enters the base price of a car.
The program should add on extra fees such as tax, license, dealer prep,
and destination charge. Make tax and license a percent of the base price.
The other fees should be set values.
Display the actua... |
# lesson 11
'''
function scoping/global variables, passing parameters
'''
# function scoping---
# namespaces follow LEGB-hierarchy: Local, Enclosed, Global, Built-In
# scope directly related to level of block indentation
# local scope: x is defined in the function
def f1():
x = 11
print("inside ... |
# lesson 04
'''
importing modules, conditions, conditional branching, code blocks
'''
# python modules---
# module is a file w/ python code, can define functions, classes, vars
# import statement: import modulename;
# from...import statement: from modulename import name1
# usage syntax: modulename.methodnam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.