text stringlengths 37 1.41M |
|---|
from Node import Node
# Creat a Doubly Linked List (Traversing / Insertion / Deletion / searching)
class DoublyLinkedList: # create a new class DoublyLinkedList
def __init__(self): # then create a constructor
self.head = Node() ... |
# Given a list of strings words representing an English Dictionary, find the
# longest word in words that can be built one character at a time by other words
# in words. If there is more than one possible answer, return the longest word with
# the smallest lexicographical order.
def longestword(words):
print('test... |
str='303'
temp_output=[]
# adding single digit characters
for i in range(len(str)):
temp_output.append(str[i])
print(temp_output)
# adding combination of two pairs
for i in range(len(str)):
for j in range(i+1,len(str)):
temp_output.append(str[i]+str[j])
print(temp_output)
count=0
for char in temp_out... |
# minimum number of coins needed to make target t
#DP using memorization technique to prevent the sample sub problem being solve again and agin
# Formula
# f(i,t) = min( f(i,t-val)+1 , f[i-1,t])
# final answer f(n-1,t)
#
import math
def changeMake(arr,target):
cache={}
def subproblem(i,t):
print(cache)
... |
# formual total zeros count > (row * col)//2
def sparsematrix(a):
zero_count=0
for i in range(len(a)):
for j in range(len(a)):
if a[i][j] == 0:
zero_count+=1
if zero_count > (len(a)*len(a[0]))//2:
return True
else:
return False
array = [ [ 1, 1, 0 ],
... |
#Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
#Example 1: Input: n = 3
#Output: ["((()))","(()())","(())()","()(())","()()()"]
def genParentheses(n):
output=[]
def backtrack(s,left,right):
if len(s) == 2 * n:
output.append(''.join(... |
a=[[0,4],[1,3]]
b=[[3,2],[5,1]]
#a+b = [[3,6],[6,4]]
for i in range(len(a)):
for j in range(len(b)):
print((a[i][j] + b[i][j]), end=' ')
print('')
|
class TreeNode:
def __init__(self,data):
self.data=data
self.children=[]
self.parent=None
def add_child(self, child):
child.parent=self
self.children.append(child)
def print_tree(self):
spaces = ' ' * self.get_level() * 3
prefix = spaces + '|__' if s... |
"""Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row
and maximum in its column.
Example 1:
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]"""
class LuckyNoMatrix:
def ... |
def rob(nums):
r1, r2 = 0, 0
for amount in nums:
temp= max(amount+r1, r2)
r1, r2 = r2,temp
print('Max amount of rob:', r2)
# formula max(val + f(n-2) or f(n-1))
def MaxFlowerPlant(arr):
a=0 #f(n-2)
b=0 #f(n-1)
for val in arr:
temp=max(val+a,b)
a,b= b,temp
pri... |
# Binary Search Iteration
def BinsearchIterative(a, val):
lower = 0
upper = len(a) - 1
while lower <= upper :
mid = (lower + upper) // 2
if val == a[mid]:
return mid
elif val < a[mid]:
upper = mid - 1
else:
lower = mid + 1
return -1
#... |
def SIN(A,B):
return A/B
def COS(A,B):
return A/B
def TAN(A,B):
return A/B
print("ATURAN TRYGONOMETRI")
while True :
print("Menu pilihan:\n")
print("1. SIN\n")
print("2. COS\n")
print("3. TAN\n")
pilih=int(input("Masukkan pilihan :"))
if pilih==1:
... |
import random
import string
from account import Account
class Credentials:
"""
Class that generates new instances of credentials
"""
list_of_credentials = []
def __init__(self,social_media,user_name,password):
"""
__init__ method that helps us define properties for our objects.
... |
#Merge sort an array
def sort(arr):
if len(arr) == 1:
return arr
mid = len(arr)//2
X = sort(arr[:mid])
Y = sort(arr[mid:])
i = j = 0
for k in range(len(arr)):
if i != len(X) and (j == len(Y) or X[i] < Y[j]):
arr[k] = X[i]
i += 1
else:
arr[k] = Y[j]
j += 1
return arr
arr = [1, 3, 5, 2, 4, 6]
pr... |
class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print "Health: {}".format(self.health)
return self
class Dog(Animal):
def __init__(se... |
class Bin_Heap:
'''
chidren at indeces 2 * i and 2 * i + 1
their parents at indeces floor(i / 2)
heap_list[0] - wasted element
'''
def __init__(self):
self.heap_size = 0
self.heap_list = [0]
def perc_up(self, k):
while k // 2 > 0:
if self.heap_list[k] < s... |
def findEmpty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
def valid(board, num, pos):
row = pos[0]
column = pos[1]
#checking rows
for i in range(len(board[0])):
if board[row][... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn import datasets, linear_model#DATASETS HAVE EXAMPLE DATASETS ,LINEAR_MODEL CONTAINS THE ALGORITHM
from sklearn.metrics import mean_squared_error, r2_score #SKLEARN.METRICS=CONFUSION MATRIX,MEAN AND R2 USED FOR TALLYING AFTER TRAINING T... |
"""Create a network proxy to sniff Tetris Friends network traffic.
This script establishes a simple TCP network proxy between the Tetris Friends server and
client, that can be used to sniff traffic, as well as inject traffic. Possible uses:
* Record games as they are being played, to create a large corpus of game play... |
def bubbleSort(lst):
for i in range(0, len(lst)):
for j in range(0, len(lst)-i-1):
if lst[j]> lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
test = [1,3,5,7,9,2,4,6,8,10,0,12,111,125,333,44]
bubbleSort(test)
print(test) |
import pandas as pd
import numpy as np
def rep(dataframe, col, choice, value):
"Tells about all the rows with which has an empty value for a particular column with an option to add / alter the values indicating empty values eg . NULL , NaN , , unknown etc and also allows a person to replace a given value choice is ... |
"""
################################################################################
Name of problem: Return Nth to Last item in linked list
Problem description:
################################################################################
"""
"""
####################################################################... |
"""
################################################################################
Name of problem: Print Power Set
Problem description:
Given an array print the power set of that array. The power set is defined
to be the set of all subsets of S, including the empty set and S itself.
######################... |
# -*- coding: utf-8 -*-
"""
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the ... |
from abc import ABCMeta, abstractclassmethod
class Instrumento(metaclass=ABCMeta):
@abstractclassmethod
def afinar(cls):
pass
@abstractclassmethod
def tocar(cls):
pass
@abstractclassmethod
def tocarEn(cls):
pass
class Guitarra(Instrumento):
def __init_... |
#!/usr/lib/python3
import random
# 从序列的元素中随机挑选一个元素
print(random.choice(range(10)))
# 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1
for i in range(10):
print("randrange(0, 1000, 2) : ", random.randrange(0, 1000, 2))
for i in range(10):
print("randrange(0, 1000, 3) : ", random.randrange(0, 1000, 3))
# 随机生成下一个实数,它在[0,1)范围内。
... |
#!/usr/bin/env python
'''
基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,
这个方法的返回值将被赋值给as后面的变量。
当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
'''
import time
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print("tr... |
import turtle
t = turtle.Turtle()
def drawT(width,height):
'''
draw a T
assume turtle facing east (0), and leave it facing east
assume pen is down
no assumptions about position.
'''
t.forward (width)
t.backward (width/2)
t.right (90)
t.forward (height)
t.left(90)
drawT(50,100)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 17:27:12 2019
@author: BlackBox
"""
def robotCheer():
an_letters = "aefhilmnorsx"
word = input('Robot cheer! Enter a word: ')
times = input('Enthusiam level (1-10): ')
times = int(times)
for letter in word:
if le... |
#!/usr/bin/env python3
#Foreign Currency
#KBowen
import locale
gblmoney = [0.0, 0.0, 0.0, 0.0, 0.0] #keep
ctry = ["Euros (EUR)", "British Pounds (GBP)", "Yen (YEN)", "Hockey Money (CAD)", "Rubles (RUB)"] #keep
def doValuation():
global ctry, gblmoney
qty = 0
cval = 0.0
grandtotal = 0.0
... |
import turtle,operator
wid = 20#柱状宽度
divi = 0.5#设置单位柱状高度与单词
k = 1300#屏幕长
h = 700#屏幕宽
x1 = 600#x轴长
def post(x,word):#绘制位置,绘制单词(数量,单词)
turtle.penup()
turtle.goto(x,-h/2 + 100)
turtle.pendown()
turtle.color("red")
turtle.seth(90)
turtle.fd(word[0] * divi)
turtle.write(word[0])
turtle... |
l1 = [-2, 11, 44, 55, -44, 22, -15, 88, -80, 10]
for x in l1:
if x > 0:
print("Number is Positive: ", x)
for x in l1:
if x < 0:
print("Number is Negative: ", x)
|
''' Positive Number '''
for x in range(-20, 15):
if x > 0:
print("Positive Number= ", x)
|
#### Armstrong Number #####
num=int(input("Enter a number= "))
def check_armstrong(num):
order = len(str(num))
sum= 0
original = num
while num> 0:
digit = num% 10
sum+= digit ** order
num= num//10
if sum == original:
return True
print("Number is armstr... |
'''Q.6 max no.of array'''
array = [11, 22, 33, 88, 44, 100, 50, 99]
max=array[0]
n=len(array)
for i in range(1,n):
if array[i]>max:
max=array[i]
print(max)
'''minimum no.of array'''
'''
min=array[0]
n=len(array)
for i in range(1,n):
if array[i]<min:
min=array[i]
print(min)
''' |
'''69. Convert a list of Tuple into Dictionary'''
x=[("Sachin",10),("Virat",18),("M.S.D",7),("Ro-Hit",45)]
print(x)
# print(type(x))
y = dict(x)
print(dict(x))
# print(type(y))
# def dic(x):
# return(dict(x))
#
# x=[("Sachin",10),("Virat",18),("M.S.D",7),("Ro-Hit",45)]
# print(dic(x)) |
class math():
def __init__(self,inp1,inp2):
self.y=inp1
self.z=inp2
def mult1(self):
w=self.y*self.z
print('multuplication=',w)
b=math(2,6)
b.mult1()
|
# coding=utf-8
# 114. 二叉树展开为链表 https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
... |
# 112. 路径总和 https://leetcode-cn.com/problems/path-sum/
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
... |
# 96 https://leetcode-cn.com/problems/unique-binary-search-trees/
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
list = [1,1,2]
if n == 0 or n == 1:
return 1
for i in range(2,n):
temp = 0
j... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def inorder(node):
... |
"""Client program to communicate with server over tcp
It firstly handshakes the server, then sends one encrpted message and closes connection
sources:
https://docs.python.org/3/library/socket.html
# pip install pycryptodome
"""
__author__ = "Kamil Skrzypkowski, Andrzej Mrozik"
import socket
import sys
from Crypto.... |
num = int(input("Enter a number: "))
a = num % 10
b = num % 100 // 10
c = num // 100
res = a * 100 + b * 10 + c
print(res)
# Добрый день Николай. Я сделала еще вариант для четырехзначного числа, для проверки себя, что я разобралась.
num = int(input("Enter a number: "))
a = num // 1000
b = num // 100 % 10
c = num //... |
"""
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns... |
# coding=utf-8
import os
# 生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用range(1, 11):
print range(1, 11)
# 生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环:
L = []
for x in range(1, 11):
L.append(x * x)
print L
# 列表生成式则可以用一行语句代替循环生成上面的list:
print [x * x for x in range(1, 11)]
# 还可以使用两层循环,可以生成全排列:
print [m+n for m in '... |
#coding=utf-8
# 高阶函数英文叫Higher-order function。
# 函数本身也可以赋值给变量,即:变量可以指向函数。
f = abs
print f(-10)
# 函数名也是变量
# 那么函数名是什么呢?函数名其实就是指向函数的变量!对于abs()这个函数,完全可以把函数名abs看成变量,它指向一个可以计算绝对值的函数!
# 传入函数
def add(x, y, f):
return f(x) + f(y)
print add(-5, 6, abs)
|
# ‐*‐ coding: utf‐8 ‐*‐
valorA = input("Introduce valor A: ")
valorB = input("Introduce valor B: ")
valorC = input("Introduce valor C: ")
if (valorA/valorB > 30):
print ((valorA/valorC*valorB)**3)
elif (valorA/valorB <= 30):
suma = 0
for i in range(2, 31, 2):
suma = i**2
pr... |
# ‐*‐ coding: utf‐8 ‐*‐
mares1 = ["mediterraneo", "cantabrico", "baltico", "adriatico", "tirreno", "egeo"]
mares2 = ["rojo", "muerto", "caspio", "negro", "arabigo", "sulu"]
mares = ["mediterraneo", "cantabrico", "baltico", "adriatico", "tirreno", "egeo", "rojo", "muerto", "caspio", "negro", "arabigo", "sulu"]
... |
# ‐*‐ coding: utf‐8 ‐*‐
def getElemento(l, i):
try:
return l[i]
except IndexError:
return None
lista = []
elementos = input("Introduce número de elementos: ")
for i in range(elementos):
lista.append(raw_input("Elemento "+str(i)+": "))
indice = input("Introduce el índice: ")... |
# ‐*‐ coding: utf‐8 ‐*‐
class Termo:
def __init__(self, cantidadCafe):
if (isinstance(cantidadCafe, (int, float, long))):
if (cantidadCafe >= 0 and cantidadCafe <= 10):
self.cantidadCafe = cantidadCafe
self.isFull = False
else:
... |
import pygame
import random
import sys
from pygame.locals import *
level = input('Level[0/1/2/3]: ')
#Create the objects
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
#load the plane image
self.image = pygame.image.load('plane.png').convert()
... |
#!/usr/bin/env python
#PROBLEM
# ================
#A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.
#An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T'... |
from battleship import BattleShip
import random
class Game:
def __init__(self, boardSize, player1Name, player2Name):
self.player1 = BattleShip(boardSize)
self.player2 = BattleShip(boardSize)
self.player1Name = player1Name
self.player2Name = player2Name
self.boardSize = boardSize
def fillBoards(... |
my_first_game = [' - ',' - ',' - ',
' - ',' - ',' - ',
' - ',' - ',' - ' ]
#first create a game bord
# switsh turn of the user and input the value
# select the winner of the game
#
game_is_going = True
num = ' X '
def the_board():
print(my_first_game[0] +'|'+ my_first_game[... |
class Book():
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
# Special methods to convert a book to string
def __str__(self):
return f"{self.title} by {self.author}"
# Special methods to return the length of a book
def __len__(self):
return self.pag... |
import math
import collections
import string
def vol(rad):
return 4.0 / 3.0 * math.pi * rad**3
def ran_check(num, low, high):
return num in range(low, high + 1)
def up_low(str):
letters = list(str)
lowercount = 0
uppercount = 0
for letter in letters:
if letter.islower():
lowercount += 1
elif letter.isup... |
# Using a default argument
def myfunction(name='NoName'):
"""Hello name
Args:
name (string): name
Returns:
string: Hello name
"""
return "Hello " + name
def main():
print("== Print doc on the insert function ==")
help([1, 2].insert)
print("== Print doc on myfunction ==")
help(myfunction)
print("== F... |
if __name__ == "__main__":
num = 15
print(f"Hexadecimal: {num} => {hex(num)}")
print(f"Binary: {num} => {bin(num)}")
print(f"pow(2, 4): {pow(2, 4)}")
print(f"pow(2, 4, 3) (last number is a modulo): {pow(2, 4, 3)}")
print(f"abs(-10): {abs(-10)}")
print(f"round(3.2): {round(3.2)}")
print(f"round(3.7): {round(3.7... |
import datetime
if __name__ == "__main__":
t = datetime.time(5, 25, 1)
print(t)
print("")
print("datetime.time.min:", datetime.time.min)
print("datetime.time.max:", datetime.time.max)
print("datetime.time.resolution:", datetime.time.resolution)
print("")
today = datetime.date.today()
print("Today:", today)
... |
def square(num):
return num**2
def check_even(num):
return num%2 == 0
def main():
print("== map ==")
array = [1, 2, 3, 4]
print("square", array, "->", [x for x in map(square, array)])
print("\n== filter ==")
print("filter even", array, "->", [x for x in filter(check_even, array)])
print("\n== lambda express... |
import random as rd
def dice():
return rd.randint(1, 6)
def main():
goal = int(input("目標点数は?"))
mPoint = 0
ePoint = 0
while(True):
# 自分のターン
print("\nYour turn!")
mini_sum = 0
input()
while(True):
print("ダイスを振りますか?")
... |
from turtle import *
from helpers import draw_circle
from movement import no_delay
import time
import settings
def draw_animation(num_frames,sleeptime):
"""Takes num_frames and sleeptime as arguments and draws the animation.
Draws 3 circles on top of eachother. With each frame, the innermost and outermost
... |
current_line =0
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file= open("test.txt")
def printt():
print("Lets print three lines ")
current_line = 0
current_line += 1
print_a_line(current_line, current_file)
printt()
|
import random
def escoge_numero(mochila):
intentos = 0
num_max = 15
num_min = 1
print('¡Estas en la papelera, y te ha tocado el juego de ESCOGE UN NUMERO!')
numero = random.randint(num_min, num_max)
print('Debes decirme en que numero estoy pensando entre ' + str(num_min) + ' y ' + str(num_max)... |
import random
lista = [1,2,3]
def pregunta1(mochila):
#pregunta uno
print('''
¿En qué fecha es el Aniversario de la Universidad Metropolitana?",
1. 22 de octubre
2. 22 de septiembre
3. 25 de octubre
4. 25 de septiembre
''')
respuesta_uno = input('''
- Coloca el numero de la respuesta... |
import tkinter
from tkinter import ttk
import crypto
COINS = [
'BTC',
'DOGE',
'XRP',
'ADA']
CURRENCIES = [
'USD',
'EUR',
'HUF']
coin_choosed, currency_choosed = False, False
def change_coin(value):
global COIN
global coin_choosed
COIN = value
coin_choosed = True
# pri... |
#!/usr/bin/python
import argparse
import sys
from itertools import *
import math
import operator
# calculate the number 1/m where m < n which has the longest repeating part of its fraction
# technique: long division. Track remainder as dividing by n, populating a dict with
# remainder -> decimal position; return [cur... |
#!/usr/bin/python
import argparse
import sys
from itertools import *
import math
import operator
# to start us off
primes = [2, 3, 5, 7, 11, 13, 17, 19]
primeSet = set(primes)
def seedPrimes(upTo):
for i in xrange(primes[-1]+2, upTo, 2):
isPrime = True
limit = int(math.sqrt(i))
for j in primes:
i... |
import unicodedata
import re
def unicode_to_ascii(s):
"""Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427"""
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
def normalize_string(s):
"""Lowercase,... |
"""
Kata: Sequence generator (6 kyu)
Description:
Write a generator sequence_gen ( sequenceGen in JavaScript) that, given the first terms of a sequence will generate a (potentially) infinite amount of terms, where each subsequent term is the sum of the previous x terms where x is the amount of initial arguments (exam... |
"""
Kata: Validate Sudoku with size `NxN` (4 kyu)
Description:
Given a Sudoku data structure with size NxN, N > 0 and √N == integer, write a method to validate if it has been filled out correctly.
The data structure is a multi-dimensional Array, ie:
[
[7,8,4, 1,5,9, 3,2,6],
[5,3,9, 6,7,2, 8,4,1],
[6,1,2, ... |
"""
Kata: Tax Calculator (7 kyu)
Description:
Write a function to calculate compound tax using the following table:
For $10 and under, the tax rate should be 10%.
For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%.
For $30 and under, the tax rate on the first $10 is s... |
"""
Kata: IPv4 Parser (6 kyu)
Description:
Problem Statement
Write a function that takes two string parameters, an IP (v4) address and a subnet mask, and returns two strings: the network block, and the host identifier.
The function does not need to support CIDR notation.
Description
A single IP address with subnet ... |
"""
Kata: Dbftbs Djqifs ("Caeser Cipher" with 1 letter shift) (6 kyu)
Description:
Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key.
Your task is to create a function encryptor that takes 2 arguments - ... |
# Sys is used to exit the program in case the libraries needed are not isntalled
import sys
try:
import cv2
except:
print("You need to install Opencv \n Run this command \n pip install python-opencv")
sys.exit(1)
#Numpy will be installed along Open-cv automatically
import numpy as np
try:
# We use matplo... |
# given a number, print it's factors
# get user input for number and set a variable for factor numbers
inp = int(input("Give me a number, any number: "))
num_of_factor = 1
# Logic
while num_of_factor <= inp:
if inp % num_of_factor == 0: # if input can be divided evenly by number, it is a factor
print(num_... |
import unittest
from simplex import Simplex
class MyTestCase(unittest.TestCase):
def test_something(self):
s = Simplex()
funcao_objetivo = [-2, -1, 1]
restricoes = [["<=", 1, 1, 2, 6], ["<=", 1, 4, -1, 4], [0, ">=", ">=", ">="]]
#Passo 0
s.forma_padrao(funcao_obje... |
import sys
from chessBoard import *
class Agent:
def __init__(self, turn, colour):
self.turn=turn #A flag that is true when its Computer's turn
self.colour=colour
self.attacked=0
self.attackedPieces=[]
self.score=0
def game(user, chessBot):
board=chessBoard()
... |
#!/bin/env python
"""
Write a function with the following signature:
title(str) -> str
It should take a string and capitalize it according to book title rules
eg:
title("a tale of two cities")
=> A Tale of Two Cities
"""
lowercase = ["a", "of", "an", "the", "to", "at", "in", "with", "and", "for", ... |
from abc import ABCMeta, abstractclassmethod
import sys
class Zoo(object):
animals = {}
def __init__(self, name):
# 动物园名字
self.name = name
@classmethod
def add_animal(cls, animal):
if animal not in cls.animals:
cls.animals[animal] = animal
if not hasa... |
import math
import sys
#Functions
def calculateSideLength(sides, radius):
degrees = math.radians(180) #convert from degrees to radians
sideLength = (math.tan(degrees/sides) * 2) / radius #Calculate the side length of a polygon based on num sides and the radius of said polygon
return sideLength
def calcu... |
# fibonacci sequence 0,1,1,2,3,5,8,13,21
# write function which takes number and print this number of item of fibonacci sequence
def fib(n):
i = 1
fibonacci = [0,1]
while i < n:
fibN = fibonacci [i-1] + fibonacci [i]
fibonacci.append (fibN)
i += 1
print (fibonacc... |
# task 1 - function takes two coordinates of two rooks on a chessboard, returns true or false if the rooks can take each other
# we supposse that chessboard has size 8 x 8 (coordinates cannot be grater than 8)
# we supposse that the two coordinates are different from each other
def rooks(l1, l2):
if l1[0] == l2[0]... |
def sortList(lst):
isListSorted = False
while not isListSorted:
i = 0
isListSorted = True
while i < len (lst) - 1:
if lst[i] > lst[i + 1]:
lst[i], lst[i+1] = lst[i+1], lst[i]
isListSorted = False
i = i + 1
return lst
... |
# IPND Stage 2 Final Project
# For this project, we shall be building a Fill-in-the-Blanks quiz.
# Our quiz will prompt a user with a paragraph containing several blanks.
# The user should then be asked to fill in each blank appropriately to complete the paragraph.
# This can be used as a study tool to help us remember... |
class Rational :
def __init__(self,numerateur,denominateur):
self.__numerateur=numerateur
self.__denominateur=denominateur
def __euclide(self,a,b):
while a != b :
if a>b :
a-=b
else :
b-=a
return a
def __add__(self,ot... |
import tkinter as tk
window = tk.Tk()
greeting = tk.Label(text="Hello, Tkinter",background="blue",foreground="yellow")
greeting.pack()
button = tk.Button(
text="Click me!",
width=5,
height=5,
bg="blue",
fg="yellow",
)
button.pack()
entry = tk.Entry(fg="yellow", bg="blue", width=50)
entry.pack()
w... |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
copy = matrix.copy()
i = 0
while i < len(matrix):
copy[i] = list(map(lambda x: x ** 2, matrix[i]))
i += 1
return copy
|
#!/usr/bin/python3
""" Module: Pascal's Triangle """
def pascal_triangle(n):
""" function that returns a list of lists of integers representing the
Pascal’s triangle of n """
list = []
if n <= 0:
return []
list =[[1]]
for i in range(0, n-1):
temporal = [0] + license[1] +[0]
... |
#!/usr/bin/python3
"""Module: Reads a text file (UTF8) and prints it to stdout"""
def read_file(filename=""):
""" function that reads a text file (UTF8) and prints it to stdout """
with open(filename, 'r', encoding='utf-8') as new_file:
print(new_file.read(), end='')
|
#!/usr/bin/python3
""" Module: script that adds all arguments to a Python list, and then save
them to a file"""
from sys import argv
save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
load_from_json_file = __import__('6-load_from_json_file').load_from_json_file
try:
new_list = load_from_json... |
import math
def solution_1_divide_by_10(number):
"""
Divide the number by 10 till it becomes zero. Number of iteration is the result.
"""
count = 0
while number > 0:
number = int(number / 10)
count = count + 1
return count
def solution_2_recursive(number):
if nu... |
# Based on Andre Torres' tutorial here:
# https://www.pythoncentral.io/finding-duplicate-files-with-python/
import os
import sys
import hashlib
def findDup(parentFolder):
# Dups in format {hash:[names]}
dups = {}
for dirName, subdirs, fileList in os.walk(parentFolder):
print('Scanning %s...' % dirName)
counter... |
#!/usr/bin/env python3
import itertools
import editdistance
def read_input():
with open('./input.txt', 'r') as input:
for line in input:
yield line
def get_unique_occurrences(input):
occurrences = [
(g[0], len(list(g[1])))
for g in itertools.groupby(sorted(input))
]
... |
import os
def parse_input() -> list[list[int]]:
parsed_input: list[list[int]] = []
with open(
os.path.dirname(os.path.abspath(__file__)) + '/input.txt',
'r',
encoding='utf-8') as f:
_tmp: list[int] = []
for line in f:
_line = line.strip()
if _lin... |
#-*- coding = utf-8 -*-
#@Time : 2020/4/15 21:47
#@Author : Shanhe.Tan
#@File : hello.py
#@Software : PyCharm
#my first python program
print("hello world") #comment
'''
comment
a = 10
print("This is :", a)
'''
'''
#format output
age = 18
print("My age is %d \r\n" %age)
age += 1
print("My age i... |
# -*- coding: utf-8 -*-
__author__ = 'Илья'
from threading import Thread, Lock
#import time, threading
lock = Lock()
def method():
lock.acquire()
# time.sleep(5)
text = "Привет Мир\n"
f = open("my.txt", "a")
f.write(text)
lock.release()
def method2():
lock.acquire()
# time.sleep(5)... |
n = int(input("enter the numbers :"))
c = []
d = 1
for i in range (n):
i = int(input(" "))
c.append(i)
d = d*i
print(d)
|
x = 0
while True:
x = int(input("Введи число в десятичной системе счисления: "))
base = int(input('Введи основание системы счисления в десятичной системе счисления: '))
number_string = ""
# обрамления каждого разряда скобочками для систем счисления с основанием, большим 10
br1 = "(" * (base > 10)
... |
from random import random
def main():
"""
Grasshoper jumps from point 1 to point n from in one direction.
|-|---|-|-...-|
0-1-2-x-4-5-...-n
Available jumps: 1 interval, 2 intervals, 3 intervals between points.
Point i=0 is not available for visiting.
Some points are not available for jum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.