text stringlengths 37 1.41M |
|---|
import argparse
parser = argparse.ArgumentParser(
description="Write sequences as text input for the two sequences to compare.")
parser.add_argument('--Sequence_1', '-s1', type=str,
metavar='', required=True,
help='Type in sequence - not FASTA just raw bases.')
parser.add_... |
from math import *
print("|\ ")
print("| \ ")
print("| \ ")
print("|___\ ")
#___________________________________________________________________
phrase = "Brazuca"
phrase_alt = "Brazooka"
print(len(phrase))
#___________________________________________________________________
print(phrase[0])
print... |
#Michael Claveria
#Python Challenge 001
#
#Goal: Unscramble the following message:
#
#g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp.
#bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.
#sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.
#
#the hint given is a pi... |
import tkinter as tk
from tkinter import Label, Canvas, Frame
from random import random
class LeaderBoard:
'''
Programmed using Tkinter, the script displays a leaderboard of
the players and their scores. The script takes in a dictionary
of players and their scores, sorts it, and displays... |
my_set={1, 3, "chalk", 90, "Apple"}
print(my_set)
# In sets we are unable to access the values with index
# print(my_set[1]) # TypeError: 'set' object is not subscriptable
#To print all the value sin the set with for loop
for x in my_set:
print(x)
# To check the valies present or not in the set
print("Apple" in ... |
from tkinter import*
from tkinter import ttk
from tkinter.font import Font
import tkinter as tk
from PIL import ImageTk,Image
import sqlite3
janela = Tk()
janela.title('Doações Casa de Apoio Betânia')
janela.geometry("370x500")
#janela.configure(background='gray')
#Banco de Dados
#Criando DB
conn = sq... |
def getMinCount(lowTemp, highTemp):
count = 0
while lowTemp != highTemp:
count += 1
if highTemp - lowTemp >= 10:
lowTemp += 10
continue
elif highTemp - lowTemp >=8:
lowTemp += 10
continue
elif highTemp - lowTemp >=3:
lo... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
num = 9999991111101 ## eta 47秒完成
# num = 600851475143/10
#num = 10976461
# num = 54499
lastNotPrime = 2
primeList =[ 2 ]
def do_main():
global num
n=num
factor=2
lastFactor=1
if n%2 == 0:
n = n/2
lastFactor =2
while n%2==0:
... |
#!/usr/bin/env python
import argparse
import os
import zipfile
parser = argparse.ArgumentParser("backup-file-list")
parser.add_argument("--file-list", "-f", required=True, type=str)
parser.add_argument("--output", "-o", default="backup.zip", type=str)
args = parser.parse_args()
def get_file_paths():
with open(ar... |
def shortestCommonPath(arr):
shortest = None
for path in arr:
if shortest == None:
shortest = path.split('/')[1:]
else:
path = path.split('/')[1:]
if len(shortest) > len(path):
shortest = path
print(shortest)
for path in arr[1:]:
... |
'''
A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).
Given a string, detect whether or not it is a pangram. Return True if it... |
def add(a,b):
return a+b
def sun(a,b):
return a-b
def add_to_sub(a,b,c):
added = add(a,b)
suned = sun(added,c)
return suned
if __name__ == "__main__":
print(add(1,2))
print(add_to_sub(10,2,4))
|
"""
python实现FTP上传下载文件
"""
from ftplib import FTP
class FileHandler(object):
def __init__(self):
self.server = "192.168.85.130"
self.user = "Administrator"
self.password = "password"
def ftp_connect(self):
ftp = FTP()
ftp.set_debuglevel(2)
ftp.connect(self.serve... |
"""This file should have our melon-type classes in it."""
""" TO DO:
Define a class for each melon type that we sell.
Add attributes for things like their name/color/imported/shape/seasons
Add a pricing method
Incorporate discounts
"""
#price info:
# Melons cost $5
# Casabas and Ogens is $1/each more
# Imported mel... |
#values
from sense_emu import SenseHat
import time
sense = SenseHat()
temperature = str(sense.get_temperature() * 9/5 + 32) + " degrees Fahrenheit"
humidity = str(sense.get_humidity()) + " %"
pressure = str(sense.get_pressure()) + " Millibars"
accelerometer = str(sense.get_accelerometer_raw()) + " Gs"
pr... |
A = int(input())
B = int(input())
temp = B
for i in range(3): # i 3 ݺض(ᰪ 3̸ 0,1,2 3 ݺ)
print(i)
print(A * (temp % 10)) # temp 10 Է B ڸ ǹ
temp = temp // 10 # temp 10 temp Ӱ
print(A*B) |
#! /usr/bin/env python3
"""
comment blocks can be turn on and off
in one character switch when preceded by #"""
#''' #< toggling off this # turns the block as a comment (it wasn't, line was mute)
print("you saw me!")
#'''
print("catched!")
"""
second example is the equivalent
of C prepropressors #ifdef 0 / #ifd... |
#! /usr/bin/env python3
"""control the whitespaces in string"""
s = 'The Little Price'
# justify string to be at least width wide
# by adding whitespaces
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1) # 'The Little Price '
print(s2) # ' The Little Price'
print(s3) # ' T... |
#! /usr/bin/env python3
"""chained comparison with all kind of operators"""
a = 10
print(1 < a < 50)
print(10 == a < 20)
|
#! /usr/bin/env python3
"""else gets called when for loop does not reach break statement"""
a = [1, 2, 3, 4, 5]
for el in a:
if el == 0:
break
else:
print('did not break out of for loop')
|
#! /usr/bin/env python3
'''
A simple way to convert arbitrary Python code into a function
'''
import math # using sin, cos and sqrt for example
''' Takes a code string and returns a ready-to-use function '''
def compile_(s):
code = """def f(x):\n return {}""".format(s) # wrap the string as a function f(x)
scope = ... |
"""
metatable with where the function recieves the dictionary and key.
"""
from collections import defaultdict
class metatable(defaultdict):
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
else:
ret = self[key] = self.default_factory(self, ... |
print("Enter your Age or Date of birth year")
age = int(input())
while True:
if age < 100:
b = 2021
a = (b - age)
c = a + 100
print('you are 100 years old in', c)
elif age > 1921:
a = age+100
print('you are 100 years old in', a)
elif age < 1921:
... |
"""
Given a FASTA file with DNA sequences, find 10 most frequent sequences
and return the sequence and their counts in the file.
Example usage:
python task2-oo.py
Results are output on CLI
"""
from task_objects import (FileHandlers, PrettyPrint, Task2Handlers)
def main():
#instantiate objects
file_handlers = Fil... |
import socket
import sys
from GameState import *
"""
Simple example pokerbot, written in python. This is an example of a bare bones,
dumb pokerbot - it only sets up the socket necessary to connect with the engine
and then always returns the same action. It is meant as an example of how a
pokerbot should communicate w... |
#!/usr/bin/python3
import random
"""
Vector class
"""
class Vector:
def __init__(self, n):
"""Constructor method"""
self.n = n
self.V = [0] * (n + 1)
def builtVector(self, m, r):
self.V[0] = m
for i in range(1, m + 1):
self.V[i] = random.randint(1, r)
... |
# 排序
arr = [{"name": "Taobao", "age": 100},
{"name": "Runoob", "age": 7},
{"name": "Google", "age": 100},
{"name": "Wiki", "age": 200}]
print(arr)
print(sorted(arr, key=lambda item: item['age']))
print(sorted(arr, key=lambda item: item['age'], reverse=True))
# 遍历字典
dict = {'a': 100, 'b': 200, 'c'... |
num1 = input('请输入第一个数字:')
num2 = input('请输入第二个数字:')
sum = int(num1) + int(num2)
print('数字{}和{}相加等于{}'.format(num1, num2, sum))
|
def bubbleSort(arr):
length = len(arr)
for i in range(length - 1):
for j in range(i + 1, length):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print("排序后的数组:")
for i in range(len(arr)):
print("%d\t" % arr[i], e... |
#!/usr/bin/python
"""
Implementation of Dutch National Flag Problem
Functions
dutch_flag_problem - Segregate 0s,1s,2s
segregate_1_0 - Segregate 0s,1s
"""
def dutch_flag_problem(a):
low = 0
mid = 0
high = len(a) - 1
while mid <= high:
if a[mid] == 0:
a[low],a[mid] = a[mid],a[low]
... |
#!/usr/bin/python
def decimal_to_binary(input):
result = []
while input > 0:
result.append(str(input%2))
input/=2
return ''.join(reversed(result))
def binary_to_decimal(input):
sum = 0
i = 0
while input:
if input%10 == 1:
sum = sum + pow(2,i)
input... |
#!/usr/bin/python
a=[1,2,5,6,7,13,56,100]
def binary_search(a,p,r,value):
if p > r:
return None
else:
mid = p + ((r-p)/2)
if (p == r):
return a[p]
if a[mid] == value:
return True
elif value < a[mid]:
return binary_search(a,p,mid-1,valu... |
#!/usr/bin/python
from double_linkedlist import double_linked_list,double_list_node
from copy import deepcopy
class binarytreenode:
def __init__(self):
self.data = None
self.left = None
self.right =None
head = None
prev = None
class binarysearchtree:
"""
Implemantation of binary sea... |
#!/usr/bin/python
import sys
a=[12, 13, 1, 10, 34, 1]
first_min = sys.maxint
second_min = sys.maxint
for i in a:
if i < first_min:
second_min = first_min
first_min = i
if i < second_min and not i == first_min:
second_min = i
print first_min
print second_min |
from turtle import *
speed(-1)
shape("turtle")
def draw_star(x, y, lengthofstar):
penup()
setpos(x, y)
pendown()
for i in range(5):
forward(lengthofstar)
right(144)
draw_star(100, 100, 100)
mainloop() |
import math
class Appearance:
"""
Appearance is : {docId , frequency}
Represents the appearance of a term in a given document, along with the
frequency of appearances in the same one.
"""
# TODO later the frequency will be something like 𝑠𝑐𝑜𝑟𝑒(𝑡_𝑖,𝑑_𝑗 )=𝑡𝑓(𝑡_𝑖,𝑑_𝑗 ) × 𝑖𝑑𝑓(𝑡... |
def player_move(player_layout):
has_move = True
while has_move:
command = input("Player turn: ").split()
if not command:
continue
if command[ 0 ] == "exit":
sys.exit(0)
c = int(command[ 0 ])
while ( not(0<c<7) or player_layout[c-1]==0)... |
############################################################
### AVL Tree Implemetation in Python ###################
############################################################
#Class Node having the essential functions
class Node :
def __init__(self,data):
self.data=data
self.parent=None
self.child(No... |
z = ['and', 'attend', 'append']
x = input().split('*')
print(x)
count = 0
for i in range (len(z)):
for b in range(len(x)):
if x[b] in z[i]:
count +=1
if count>=len(x):
print("0",z[i])
count = 0 |
names = ['Frendy','Fauzan','Fiqhy','Jerdy','Handy','Jason','Christoper','Joshua']
for i in range (0,8):
message = "Hello " + names[i] + ", How are you today?"
print(message) |
import matplotlib.pyplot as plt
from random import randint
def function(x):
return x ** 2 - 3 * x + 4
list = [x ** 2 - 3 * x + 4 for x in range(26)]
# Supposed range of x = 25
# x min = 0, x max = 25, y min = 0, y max = 600
x = [randint(0,25) for i in range(4001)]
y = [randint(0,600) for a in range(4001)]
count = ... |
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def getHour(self):
return self.hour
def getMinute(self):
return self.minute
def getSecond(self):
return self.second
def setHour(self, h... |
#This program print how many distinct number of modulo 42
def main():
y = []
m = 42
for i in range(10):
x = int(input())
y.append(x%m)
print(len(set(y)))
main() |
from Jude_Assignment.Book_Store.Book import *
Author_Data = {
'Test1' : ['test@gmail.com','male'],
'Test2' : ['test2@gmail.com', 'female']
}
Book_Data = {
'Gude' : [['Test1','Test2'], 12000, 5],
'Gude2' : [['Test1','Test2'], 12000, 5],
'lol' : [['Test1','Test2'], 12000, -1]
}
password = 'TEST1234'... |
pet_owner = {
"Jane": "1",
"Goe": 1,
"Text" : ["1","3"]
}
pet_owner["Text"].append(input())
pet_owner["Hendy"]= pet_owner.pop['Jane']
for i,j in pet_owner.items():
print(i, j) |
class animal():
def __init__(self, name, type, data_type, counter, listing, price):
self.listing = listing
self.type = type
self.counter = counter
self.name = name
self.data_type = data_type
self.price = price
def print_animal(self):
for i, j in self.type... |
a=12
b=22
print(f"value of a is {a} value of b is {b} ")
a,b=b,a
print(f"value of a is {a} value of b is {b} ")
name="vivek"
print("name will be anything".split())
print(name[::-1])
print(name[-1])
print("find factorial")
def fact(n):
if n==1:
return n
else:
return n*fact(n-1)
print(fact(5))
pr... |
#####################################
#2.01
#####################################
def min_enclosing_rectangle(radius, x, y):
'''(float, float, float) -> tuple
Preconditions: radius and x and y are non-negative numbers
Return coordinates of bottom-left corner of triangle containing the circle'''
i... |
import sys
import csv
class FileCombiner(object):
def __init__(self, includ_filename = True):
self.includ_filename = includ_filename #show filename column flag
def display_csv(self, filename):
if filename.endswith('.csv'):
with open(filename) as csv_file: # different variable
... |
def check_palindrome(sentence):
"""
This function takes a word or a sentence and
determines whereather is it palindrome or not.
Case and any special characters should be ignored.
"""
import string
not_special = string.ascii_uppercase + string.ascii_lowercase
c_list = [x for x in list(sen... |
# coding: utf-8
import functools
import inspect
# This is our decorator, it's a function that takes original
# function (func) and return a modified function (wrapper)
def apply_type(func):
# This decorator let us transpose the meta information
# of func on our new function wrapper
@functools.wraps(func)... |
#!/usr/bin/env python
# Name: Michael Stroet
# Student number: 11293284
"""
This script scrapes IMDB and outputs a CSV file with highest rated movies.
"""
import csv
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
import re
TARGET_... |
import unittest
from Board.Board import *
from Game.Game import *
class test(unittest.TestCase):
def setUp(self):
self.__game = game()
self.__board = board()
def test_board(self):
self.__board = [[0]*9,[0]*9,[0]*9,[0]*9,[0]*9,[0]*9,[0]*9,[0]*9,[0]*9]
self.assertEqual(self.__boa... |
from string import ascii_uppercase as ascii_u
import re
from collections import Counter
def process(sent):
result = {}
cleaned_sent = "".join(re.findall("[a-zA-Z]+", sent)).upper()
for a in ascii_u:
result[a] = cleaned_sent.count(a)
return result
def get_final_data(result, pivot="key", rev=F... |
"""
A short program that prints each number from 1 to 100 on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
"""
def fizzBuzz(lim):
for ... |
def check_email(s):
try:
username,url = s.split('@')
website = url.split('.')[0]
ext = url.split('.')[-1]
except ValueError:
return False
#import pdb;pdb.set_trace()
if not username.replace('-','').replace(".","").replace('_','').isalnum():
return False
if no... |
val = input('请输入带温度');
if val[-1] in ['C', 'c']:
f = 1.8 * float(val[0:-1]) + 32
print(f)
elif val[-1] in ['F', 'f']:
c = (float(val[0: -1]) - 32)
print(c);
else:
print('输入有误')
|
# resize_image.py
from PIL import Image
def resize(input_image_path, output_image_path, size):
image = Image.open(input_image_path)
width, height = image.size
print(f"The original image size is {width} wide x {height} high")
resized_image = image.resize(size)
width, height = resized_image.size
... |
# draw_rectangle.py
from PIL import Image, ImageDraw
def rectangle(output_path):
image = Image.new("RGB", (400, 400), "blue")
draw = ImageDraw.Draw(image)
draw.rectangle((200, 100, 300, 200), fill="red")
draw.rectangle((50, 50, 150, 150), fill="green", outline="yellow",
width=3)
... |
# The program asks the user name and age
# of his or her dog
# Then returns a phrase Your dogXX's human age is XX
# At the end of each prompt, a space is include
# So that the answer does not stay attached
# to the question
# Also given there is a single quote in the string
# The string is deliminated by double strin... |
# test whether a word is palindrome
# works only without punctuation nor space
def test_if_palindrome(target):
if len(target) <= 1:
return True
else:
if target[0] == target[-1]:
return test_if_palindrome(target[1:-1])
else:
return False
def test_if_palindrome_... |
import turtle
import random
turtles = []
def setup():
global turtles
startline = -620
screen = turtle.Screen()
screen.setup(1290, 720)
# the above setup had seemed to be too much repetation
# which is not true coz there are two setups to do with Screen
# btw tried to append the dots toget... |
# Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, -0.125,… Количество элементов (n) вводится с клавиатуры.
import sys
def sum_progr(n):
if n == 1:
return 1
else:
return 1 + sum_progr(n - 1) / -2
# "lesson4_1.sum_progr(10)"
# 1000 loops, best of 5: 1.61 usec per loop
# ... |
def ageMap(input):
out = {}
el = ""
odd = True
for i in input:
if(odd):
el = i
odd = False
else :
if i in out:
out[i].append(el)
else:
out[i] = [el]
odd = True
return out
inp = ['a',20,'b',21,... |
name = "Yeimar"
print(name) # imprime el valor de la variable
#Case sensitive
book = "El lobo"
Book = " 100% Max "
print(book)
print(Book)
# en python la variable book y Book, son totalmente diferentes ya que aplica case sensitive...
x,name = 100, "Yeimar" # Definimos en una sola linea
print(x,name); # Imprimimos e... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
from datetime import datetime, timedelta, timezone
now = datetime.now()
print(now)
now + timedelta(days=2, hours=4)
# %a %b %y are three-letter abbreviation of week, month and year
# %A %B %Y are full-letter of week, month and year
# #d %H %M represent for day hour and min... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
class Animal(object):
def __init__(self, name, color):
self.__name = name
self.__color = color
# self.__class__.__name__ 获取当前类的名字
# __str__
def __str__(self):
return '%s object (name: %s)' % (self.__class__.__name__, self.__name)
... |
# Import needed modules
import xml.etree.ElementTree as ET
# Possible import lxml
import urllib.request
import csv
import datetime
# Function that creates files to write to
def create_files():
# Store datetime information for file naming
current_day = datetime.date.today()
# User input to decide the file... |
global_var = 'global_var'
def func():
# nonlocal global_var # SyntaxError: no binding for nonlocal 'global_var' found
global_var = 'global_var_local_use'
# nonlocal global_var # SyntaxError: name 'global_var' is assigned to before nonlocal declaration
print(global_var)
# nonlocal global_var # SyntaxErr... |
def func():
for i in [0, 1, 2]:
try:
print('try 「yieldだ、別れよう」'.format(i))
yield
finally:
print('finally「私を捨てるの?させないわ」')
for i in func():
pass
print('The End.')
|
class MyClass:
def __init__(self, var):
self.var = var
def method(self):
print('var =', self.var)
a = MyClass('a')
b = MyClass('b')
a.method()
b.method()
MyClass.method(a)
MyClass.method(b)
MyClass.method(*[a])
# TypeError: method() takes 1 positional argument but 2 were given
#a.method(a)
... |
s = 'abc'
it = iter(s)
print(it)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
|
class Human:
def __init__(self): self.__intro()
def intro(self): print('Human')
__intro = intro
def show_human(self): self.__intro()
class Programmer(Human):
def __init__(self):
# super().__init__()
# ----- Human.__introを上書きする -----
# 親クラスインスタンスの関数オブジェクトが参照できない
# super(... |
class Human:
def __init__(self, name='none_name'):
if None is name or 0 == len(name.strip()): self.name = 'none_name'
else: self.name = name
self.name = ''
def walk(self):
print('walk.')
class Programmer(Human):
def __init__(self, name='none_name', skills=None):
super... |
#PF-Assgn-36
def create_largest_number(number_list):
number_list.sort(reverse = True)
largest_number = 0
for num in number_list:
largest_number = largest_number * 100 + num
return largest_number
number_list=[23,45,67]
largest_number=create_largest_number(number_list)
print(larges... |
#DSA-Assgn-12
class Stack:
def __init__(self, max_size):
self.__max_size = max_size
self.__elements = [None] * self.__max_size
self.__top = -1
def get_max_size(self):
return self.__max_size
def is_full(self):
if (self.__top + 1) >= self.get_max_size():
r... |
#DSA Exer-6
import copy
class Stack:
def __init__(self, max_size):
self.__max_size = max_size
self.__elements = [None] * self.__max_size
self.__top = -1
def get_max_size(self):
return self.__max_size
def is_full(self):
if (self.__top + 1) >= self.get_max_size():
... |
#DSA-Exer-19
def swap(num_list, first_index, second_index):
temp = num_list[first_index]
num_list[first_index] = num_list[second_index]
num_list[second_index] = temp
def find_next_min(num_list, start_index):
min_index = start_index
for i in range(start_index + 1, len(num_list)):
if num_li... |
#PF-Assgn-39
#This verification is based on string match.
#Global variables
menu=("Veg Roll", "Noodles", "Fried Rice", "Soup")
quantity_available=[2,200,3,0]
def place_order(*item_tuple):
for i in range(0, len(item_tuple)):
if i % 2 == 0:
item = item_tuple[i]
if item in menu:
... |
#DSA-Tryout
import random
def find_it(num, element_list):
no_of_guesses = 0
for number in element_list:
no_of_guesses += 1
if number == num:
print("Success")
break
else:
print("Try again")
print("Guessed in", no_of_guesses, "tries")
#Initializes... |
#PF-Assgn-20
def calculate_loan(account_number, salary, account_balance, loan_type, loan_amount_expected, customer_emi_expected):
eligible_loan_amount = 0
bank_emi_expected = 0
eligible_loan_amount = 0
eligible = False
#Start writing your code here
#Populate the variables: eligible_lo... |
#PF-Assgn-31
def check_palindrome(word):
flag = False
for i in range(0, len(word)):
if word[i] == word[-(i+1)]:
flag = True
else:
flag = False
break
return flag
status = check_palindrome("malayalam")
if(status):
print("word is palin... |
#DSA-Assgn-18
def find_unknown_words(text, vocabulary):
words = text.split(" ")
unknown_words = set()
for word in words:
if word not in vocabulary:
unknown_words.add(word)
if len(unknown_words) <= 0:
return -1
return unknown_words
#Pass different values of... |
import sqlite3
class User:
def __init__(self):
self.db = sqlite3.connect('test.db') #Create a new database after test case!!
try:
self.db.execute('''CREATE TABLE tickets
(TICKETNO TEXT PRIMARY KEY NOT NULL,
GAMEID INTEGE... |
#!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:wchao118
@license: Apache Licence
@file: Maximum Subarray.py
@time: 2019/03/28
@contact: wchao118@gmail.com
@software: PyCharm
"""
"""
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
"""
class Solution(object)... |
QQQ =int(input("請輸入n:"))
WWW =int(input("請輸入k:"))
EEE =int(0)
RRR =int(QQQ)
TTT =int(0)
while(QQQ//WWW>=1):
QQQ =RRR
EEE +=QQQ
RRR =(QQQ+TTT) // WWW
TTT =QQQ % WWW
print("Peter可以抽",EEE,"支紙菸")
|
Q1 = int(input(":"))
for i in range(1,Q1,2):
for o in range(1,Q1,2):
print(" ", end="")
print(str(i))
for i in range(1,Q1+2,2):
print(str(i),end="")
for i in range(1,Q1,2):
print(str(Q1-i-1),end="")
print()
for i in range(1,Q1,2):
for o in range(1,Q1,2):
print(" "... |
'''
Created on Mar 29, 2014
@author: psgada
'''
import sys
import Queue
'''
Write unittest module to test the individual modules of the Binary search tree class
'''
'''
Define a binary tree node class
A node of a binary search tree contains a left pointer which points to left subtree,
a right pointer ... |
# Gapminder Data: employment levels, life expectancy, GDP, school completion rates
# 5 questions: correlation between GDP (economic growth) and employment levels
# correlation between GDP (economic growth) and school completion rates
# correlation between GDP (economic growth) and life expectancy
# correlation between ... |
list_of_scores = input("Input a list of scores: ").split()
for n in range(0, len(list_of_scores)):
# list_of_scores[n] = int(list_of_scores[n])
list_of_scores.sort()
highest_score = list_of_scores[-1]
print(list_of_scores)
print(highest_score) |
from numpy import random
import math
import numpy as np
import matplotlib.pyplot as plt
class Neural:
#neural structure is
# o - o o
# o \ o o
# \d o
# O O -->bias
def __init__(self,inputs,array_output,n_input,n_hidden,n_output):
self.input = inputs
for i in range(len(self.input)):
self.input[i]=... |
"""
Problema da Calculadora:
Construa uma calculadora com as 4 operações básicas: soma, subtração, adicão, multiplição e divisão.
Faça 3 tipos de calculadora: uma em que o usuário inpute 2 números e depois o sinal da operação; outra que ele inpute o primeiro número, depois o sinal, depois o outro número e, por fim,... |
def main():
vDict = {}
with open('test.txt') as f:
for line in f:
tempList = line.split('\t')
vDict[int(tempList[0])] = []
for v in tempList[1:]: # use [1:-1] for actual graph, [1:] for test
tempstr = v.split(',')
vDict[int(tempList[0])].append((int(tempstr[0]), int(tempstr[1])))
start = ... |
from math import pi
def circle_area(radius):
# if type(radius) not in [int, float]:
# raise TypeError("Radius must be a non-negative, real number.")
# if radius < 0:
# raise ValueError("Radius cannot be a negative number")
return pi * radius ** 2 |
import time
from datetime import datetime as dt
"""A list of the websites to be blocked"""
sites_to_block = [
'www.facebook.com', 'facebook.com',
]
"""Different operating system host file location where we are going to add a list
of websites we want to block"""
Linux_host = '/etc/hosts'
MacOs_hos... |
class Calculator:
def __init__(self, number):
self.number = number
self.rm1 = number - 1
self.rm2 = number - 2
self.rm3 = number - 3
self.rm4 = number - 4
self.rm5 = number - 5
self.ra1 = number + 1
self.ra2 = number + 2
self.ra3 = number + 3
... |
#################################################################################
# Roots #
# #
# PROGRAMMER: Maxwell Solko ... |
"""
READ DATA
"""
import sqlite3
import pandas as pd
def read_data(db_path, query_path, index):
"""
Read data from the SQLite Database
Function Parameters:
db_path: database path
query_path: sql query path
index: index of the dataframe after the data is read from database
"""
... |
"""Simple text manipulation utilities"""
def trim_after(s, pattern):
"""Trim input string starting pattern.
Leading and trailing whitespace is stripped.
Parameters
----------
s : Input string
pattern : String used to locate trim location
Returns
-------
t : trimmed string
... |
# Time Complexity :O(n)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode :yes
# Any problem you faced while coding this :no
#Leetcode : 994
# You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.