text stringlengths 5 121k |
|---|
def main():
title = 'a clash of KINGS'
minor_words = 'a an the of'
officialTitle = title_case(title, minor_words)
print(officialTitle)
def title_case(title, minor_words):
titleWordList = list()
minorWordList = list()
officialTitle = ""
if title != '':
print("Yorgy Shm... |
number = int(input())
num = len("Hello World")
HW =("Hello World")
j = 0
if number == 0:
print("Hello World")
elif number > 0:
while j < num:
print(HW[j:j+2])
j +=2
else:
for i in "Hello World":
print(i)
|
import turtle,time
def drawGap():
turtle.penup()
turtle.fd(5)
def drawLine(draw):
drawGap()
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
drawGap()
turtle.right(90)
def drawDigit(digit):
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
drawLine(True)... |
import turtle as t
t.pencolor("pink")
t.left(90)
def main():
for i in range(10):
t.circle(10,360)
t.penup()
t.fd(20)
t.pendown()
t.penup()
t.right(180)
t.fd(200)
t.left(90)
t.fd(20)
t.left(90)
t.pendown()
for i in range(10):
main()
t.don... |
from sys import argv
script, filename = argv
print("Let's open the file:")
target= open(filename, 'r+')
print("Let's erase the content.")
target.truncate()
print("Let's write something")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
target.write(line1)
target.write("\n")
target... |
from sys import argv
a,x,y,z = argv
print(f"the first is {x}")
print(f"the second is {y}")
print(f"the third is {z}")
print(input("What you want is ")) |
def partisi(A, awal, akhir):
nilaiPivot = A[awal]
penandaKiri = awal
penandaKanan = akhir
selesai = False
while not selesai:
while penandaKiri <= penandaKanan and A[penandaKiri] <= nilaiPivot:
pendanaKiri = penandaKiri + 1
while A[penandaKanan] >= nilaiPivot... |
import time
import random
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
op = input("請輸入Y開始遊戲")
print(list1)
t0 = time.time()
while op == 'y' or op == 'Y':
for i in range(0, 10):
k = random.randrange(0, 26)
... |
import argparse
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
parser.add_argument('-arg1', '--argument1' , action="store", required=True, help='Help for option X')
... |
name_list = []
order = 0
for count in range(6):
order + 1
name = input("Please input a name: ")
name_list.append(name)
print(name_list)
while 1:
print("Please input the names you wish to view")
view = int(input("From: "))
end_view = int(input("To: "))
print(name_list[view:end_v... |
import networkx as nx
from matplotlib import pyplot as plt
def graphviz(graph, edgecolor='grey', nodecolor='purple'):
"""
Parameters
----------
graph : graph object
A graph object prepared by the graphprep function
edgecolor : string
Optional color selection for visualization
nod... |
from pprint import pprint
caves = {}
with open('input.txt') as f:
for line in f:
cave, connected_to = line.strip().split('-')
if cave in caves:
caves[cave].add(connected_to)
else:
caves[cave] = {connected_to}
if connected_to in caves:
caves[conne... |
"""
Routines for caching web queries
"""
import requests
from bs4 import BeautifulSoup
import pandas as pd
import six
_web_cache = dict()
def get_web_page(url, force):
"""
Gets a web page from the web, or from the local cache, in case it is cached.
Arguments:
url - the URL to retrieve
force - if ... |
import math
from collections import deque
def calculate_steps_from_number_to_one(number):
operation_list = deque([number])
step_list = [0] + [math.inf for _ in range(number)]
prev_list = [math.inf for _ in range(number)]
if number != 1:
for num in range(1, number):
for value in (nu... |
import math
def diff(char1, char2):
return 1 if char1 != char2 else 0
def _edit_distance(distance, i, j, str1, str2):
if distance[i][j] == math.inf:
if i == 0:
distance[i][j] = j
elif j == 0:
distance[i][j] = i
else:
insert = _edit_distance(distanc... |
import cv2
import sys
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
count = 10
while True:
ret, frame = video_capture.read()
if not ret: continue
if(count % 40 == 0):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces... |
from random import randint
def introduce():
print("这是一个石头剪刀布的游戏")
print("请点击开始进行游戏")
print("每赢一局分数加一,采取五局三胜制")
def got():
f = True
print("请输入“石头”或“剪刀”或“布”")
while f:
x = 0
n = str(input())
if n in ["石头"]:
x = 1
f = False
elif n in ["剪刀"... |
"""
Created on Wed Nov 4 19:09:11 2020
@author: LENOVO i5
"""
a = eval (input("masukan nilai a: "))
b = eval (input("masukan nilai b: "))
hasil = a+b
print ("variable a = ",a)
print ("variable b = ",b)
print ("hasil penggabungan %d & %d = %d" % (a, b, hasil))
print ("KONVERSI NILAI VARIABLE")
a = int(a)
b = int(b... |
import argparse
def say_something(phrase):
"""Change this however you'd like!"""
print("testphrase1")
print(phrase)
print("testphrase2")
def cli():
"""Command line interface"""
parser = argparse.ArgumentParser(
description="Demo for bioinformatics and genomics program at UO.")
... |
import random
import math
def generate(numPoints):
result = []
for i in range(0, numPoints):
x = random.uniform(-6,6)
y = random.uniform(-6,6)
color = 1 if distance((0,0), (x,y)) < 3 else 0
result.append((x,y,color))
return result
def distance(pointFrom, pointTo):
diff = (pointTo[0] - pointFro... |
import math as m
from complex import *
def test_add():
"""
Test addition for Complex with Complex, complex, int and float
"""
z = Complex(1, -2)
w = Complex(1, 1)
assert (z + w) == Complex(2, -1)
assert (z + (1+1j)) == Complex(2, -1)
assert (z + 2) == Complex(3, -2)
asser... |
import os
import io
from pandas import DataFrame
import pandas as pd
from sklearn .feature_extraction.text import CountVect... |
"""
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
import re
... |
import tkinter as tk
root = tk.Tk()
root.title("This is my template")
root.config(bg='#123456')
root.resizable(width=True, height=True)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.geometry("%dx%d+%d+%d" % (screen_width, screen_height, 200, 300))
label = tk.Label(root, t... |
"""
@Author: Alex Waweru
"""
import timeit
def dynamic_programming_change_maker(coin_value_list, change, min_coins, coins_used):
for cents in range(change+1):
coin_count = cents
new_coin = 1
for j in [c for c in coin_value_list if c <= cents]:
if min_coins[cents-j] + 1 < coin_count:
... |
class DataFile:
def get_handle(file_location):
in_file = open(file_location, "r")
return in_file
def read_file(file_handle, lines_to_read, offset):
end_of_file = False
file_dict = {}
count = 0
file_handle.seek(offset)
while count <... |
"""
Room Allocation System
Usage:
room.py create_room <room_name> <room_type>...
room.py add_person <person_name> <emp_type>...
room.py print_room <room_name>
room.py print_allocations [-o=filename]
room.py print_unallocated [-o=filename]
room.py reallocate_person <person_identifier> <new_room_name
room.p... |
'''
Basic approach => Traverse from left to right first and store product of element to left for each index in an array. Traverse from right to left in next loop and save the product of elements to the right for each index in another array. Take product of the two arrays to get the answer array and return... |
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
def binary_search(arr, target):
first = 0
last = len(arr) -1
while first <= last:
mid... |
def two_or_odd_numbers_between(start, end):
if start == 2:
return [2, *range(3, end + 1, 2)]
range_start = start + 1 if start % 2 == 0 else start
return range(range_start, end + 1, 2)
|
import importlib
def get_all_candidates(ballots):
'''(list)->list
Given a list of strings, a list of lists, a list of dictionaries, or a
mix of all three, this function returns all the unique strings in this
list and its nested contents.
([{'GREEN':3, 'NDP':5}, {'NDP':2, 'LIBERAL':4},['CPC', 'NDP'... |
import json
filename = 'username2.txt'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input('What is your name? ')
with open(filename,'w') as f:
json.dump(username, f)
print(f"We'll remember your {username} for your return!")
else:
... |
import json
def check_fornumb():
"""File name"""
filename = 'fav_number.json'
try:
with open(filename) as f:
number = json.load(f)
except FileNotFoundError:
return None
else:
return number
def fav_numb():
filename = 'fav_number.json'
try:
number =... |
import matplotlib.pyplot as plt
'''Temperature graphics'''
'''Graphic'''
'''Newton Universal Gravitation Law'''
def draw_graph(x,y):
plt.plot(x,y,marker="o")
plt.xlabel("Distance in meters")
plt.ylabel("Gravitational force in newtons")
plt.title("Gravitational force an... |
import numpy as np
from layers import (
FullyConnectedLayer, ReLULayer,
ConvolutionalLayer, MaxPoolingLayer, Flattener,
softmax_with_cross_entropy, l2_regularization
)
class ConvNet:
"""
Implements a very simple conv net
Input -> Conv[3x3] -> Relu -> Maxpool[4x4] ->
Conv[3x3] -> Relu... |
import numpy as np
from layers import (
FullyConnectedLayer, ReLULayer,
ConvolutionalLayer, MaxPoolingLayer, Flattener,
softmax_with_cross_entropy, l2_regularization
)
class ConvNet:
"""
Implements a very simple conv net
Input -> Conv[3x3] -> Relu -> Maxpool[4x4] ->
Conv[3x3] -> Relu... |
print('welcome to the tip calculator')
totalBill = input('what was the total bill? $')
numOfPeople = input('how many people to split the bill?')
tipPercentage = input('what percentage tip would you like to give? 10, 12 or 15?')
result = (float(totalBill) / float(numOfPeople))+ float(totalBill)/float(numOfPeople)*(f... |
sudoku = ['', '', '', '', '', '', '', '', '']
for i in range(len(sudoku)):
sudoku[i] = input("Enter row " + str(i + 1) + ':')
def validSudoku(sudoku):
for row in sudoku:
if ''.join(sorted(row)) != '123456789':
print('a')
return False
for i in range(9):
... |
import threading
def set_interval(func, sec):
"""Automatic function caller.
Keyword arguments:
func -- the function to call repeatedly
sec -- time interval to call func
"""
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start... |
x = [100,110,120,130,140,150]
multiplied_list=[element*5 for element in x]
print(multiplied_list)
def divisible_by_three():
x=range(10,100)
for y in x:
if y%3==0:
print(y)
x = [[1,2],[3,4],[5,6]],
flat_list = []
for sublist in x:
for num in sublist:
flat_list.append(num)
... |
import math as m
def func_d1(x,y):
return x+y+(x*y)
def func_d2(x,y):
return ((1+x)*func_d1(x,y)) + y + 1
def func_d3(x,y):
return ((x+1)*func_d2(x,y)) + (2*func_d1(x,y))
def main():
x0 = float(input("Enter x_0: "))
y0 = float(input("Enter y_0 i.e y(x_0): "))
xn = float(input("Enter ... |
"""
7. Reverse Integer
Easy
2476
3842
Favorite
Share
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
... |
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
fnum =float(num)
except:
print ("Invalid input")
continue
if largest is None:
largest = fnum
elif fnum > largest:
largest = fnum
... |
import csv
import sqlite3
with open('Pesquisa500.csv') as file:
fileReader = csv.reader(file, delimiter=',')
dbConec = sqlite3.connect("pesquisa500.db")
db = dbConec.cursor()
db.execute('CREATE TABLE questao( id INTEGER PRIMARY KEY AUTOINCREMENT, descricao VARCHAR(... |
def even_elements(input_list):
if type(input_list) == list:
return [input_list[i] for i in range(len(input_list)) if i % 2 == 1]
else:
raise TypeError
|
import unittest
from src.fizzbuzz import FizzBuzzer, Checker
class FizzBuzzerTest(unittest.TestCase):
def setUp(self):
self.m = FizzBuzzer((Checker(3, 'Fizz'), Checker(5, 'Buzz'), Checker(7, 'Bang')))
def test_one_two(self):
assert self.m.say(1) == "1"
assert self.m.say(2) == "2"
def test_fizz(self):
ass... |
import pygame
import math
from Calculator import Calculator
from globals import *
class Screen:
init_text = '0'
error = False
def __init__(self):
self.text = '0'
self.x = 100
self.y = 80
self.width = 390
self.height = 80
self.calc = Calculator()
def dra... |
import turtle
colors=['red','yellow','blue','green','orange','pink']
screen=turtle.Screen()
t=turtle.Turtle()
t.speed(0)
screen.bgcolor('black')
for x in range(300):
t.pencolor(colors[x%6])
t.width(3)
t.forward(x)
t.left(20)
|
"""
[ref] https://codeup.kr/problem.php?id=1055
Question:
1. take two true(1) or false(0)
2. print true when any of them is True at least
"""
import sys
x, y = map(int, sys.stdin.readline().rstrip().split())
x, y = map(bool, [x, y])
OrGate = lambda x, y: x or y
print(int(OrGate(x, y)))
|
"""
[ref] https://codeup.kr/problem.php?id=1029
Question:
1. get one real number in range 0 ~ 4,294,967,295
2. print it up to 11 decimal places
"""
data = float(input())
print("%.11f" %data) |
"""
[ref] https://codeup.kr/problem.php?id=1036
Question:
1. take one English letter
2. print it out as the decimal value of the ASCII code table.
"""
letter = input()
print(ord(letter))
"""
Program to find the ASCII value of a character:
https://beginnersbook.com/2019/03/python-program-to-find-ascii-... |
"""
[ref] https://codeup.kr/problem.php?id=1069
Question:
1. receive evaluation as letters (A, B, C, D ...)
2. print it as comment
평가 내용
평가 : 내용
A : best!!!
B : good!!
C : run!
D : slowly~
others : what?
"""
eval = input()
comment = {"A":"best!!... |
"""
[ref] https://codeup.kr/problem.php?id=1026
Question:
1. get hour:minute:second
2. print only 'minute' part
"""
h, m, s = input().split(":")
print("%d" %(int(m))) |
"""
[ref] https://codeup.kr/problem.php?id=1013
Question:
1. get two integers
2. print them
"""
import sys
a, b = map(int, sys.stdin.readline().split())
print(a, b)
|
"""
[ref] https://codeup.kr/problem.php?id=1037
Question:
1. take one decimal ineger
2. print it out in ASCII characters
"""
num = int(input())
print(chr(num))
"""
Program to find the ASCII value of a character:
https://beginnersbook.com/2019/03/python-program-to-find-ascii-value-of-a-character/
""" |
'''鸭子类型,多态'''
class Cat:
def say(self):
print("I am a cat")
class Dog:
def say(self):
print("I am a dog")
def __getitem__(self):
return "bob8"
class Duck:
def say(self):
print("I am a duck")
animal_list = [Cat,Dog,Duck]
for animal in animal_list:
animal().say()
... |
from collections.abc import *
from _collections_abc import __all__
class Base:
def answer(self):
print("This is base class")
def say(self):
print("hello " + self.name)
class MetaClass(type):
def __new__(cls, *args, **kwargs):
print("This is MetaClass")
return super().__new__(cls,... |
class Company:
def __init__(self, name, staffs=[]):
self.name=name
self.staffs=staffs
def add(self,staff):
self.staffs.append(staff)
com1 = Company("com1")
com2 = Company("com2")
com1.add("bob1")
com2.add("bob2")
print(com1.staffs)
print(com2.staffs)
print(com1.staffs is com2.staffs... |
import argparse
import sys
import re
def calcSleepTime(argc, argv):
match = re.match(r'(\d+):(\d\d)', argv)
if match is None:
match = re.match(r'(\d*)', argv)
hour = int(match.group(1))
if (hour > 12):
print("Must be between (1-12)")
exit(1)
count = 8
... |
""""
this is class 02 file
1 Varibale
2 Data type: integer, string,boolean,none
3 Data structure : We can store multiple data type and their relationship in string
"""
integer_variable =3
print(integer_variable,id(integer_variable),)
string_variable ="This is my sinle line string"
string_variable_2= "This is my" ... |
import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def Int_shutdown(channel):
os.system("sudo shutdown -h now")
GPIO.add_event_detect(18, GPIO.FALLING, callback = Int_shutdown, bouncetime... |
a = float(input())
print("A=%.4f" % ((a**2)*3.14159))
|
def Fibonacci(n):
if(n==2):
return 2;
elif(n==1):
return 1;
return Fibonacci(n-1)+Fibonacci(n-2)
def Find():
i=1;
sum=0;
while(Fibonacci(i)<=4000000):
if(Fibonacci(i)%2==0):
sum+=Fibonacci(i)
i+=1
print(sum)
|
"""
Created on Sun Aug 25 19:51:00 2019
@author: Administrator
"""
from pandas import Series;
x = Series(['a', True, 1], index=['first', 'second', 'third'])
x = Series(['a', True, 1]);
print(x[1]);
x[2]
"""
#不能追加单个元素
x.append('2')
#追加一个序列
n = Series(['2'])
x.append(n)
#需要使用一个变量来承载变化
x = x.append(n)
'2' in... |
import unittest
from poker.card import Card
from poker.validators import FlushValidator
class FlushValidatorTest(unittest.TestCase):
def setUp(self):
self.two_of_diamonds = Card(rank='2', suit='Diamonds')
self.three_of_diamonds = Card(rank='3', suit='Diamonds')
self.five_of_diam... |
tempSquares = []
tempSum = []
n = 100
for i in range(1,n+1):
tempSum.append(i)
i = i ** 2
tempSquares.append(i)
squareOfSums = sum(tempSum) ** 2
sumOfSquares = sum(tempSquares)
print ("Sum of squares: " + str(sumOfSquares))
print ("Square of sums: " + str(squareOfSums))
print (str(squareOfSums) + " - " + str(su... |
a=int(input('enter a num'))
try:
if a>4:
print('>4')
else:
print('<4')
except valueerror:
print('value in digit')
finally:
print('success')
|
p=float(input("input princple"))
t=float(input("time"))
r=float(input("rate of intresst"))
def simpleIntrest(p,t,r):
si=0
si=p*t*r/100
print("simple intrest is"+str(si))
simpleIntrest(p,t,r)
def compoundIntrest(p,t,r):
amount=0
amount=p*((1+(r/100))**t)
ci=amount-p
print("compo... |
import tkinter
from tkinter import *
window=tkinter.Tk()
window.title('Calculator')
window.geometry('200x190+300+200')
ch=StringVar()
pole = Entry(window, width = 35, font = 'Arial 8', textvariable=ch)
pole.grid(column = 0)
pole.place(x=0, y=1)
pole.pack()
def enter(c):
return ch.set(ch.get() + c)
def result(c):... |
import math
import random
n=int(input('Введите номер задачи: '))
if n == 7.1:
a,b,c=map(int,input('Введите a,b,c').split())
p=(a+b+c)/2
s=math.sqrt(p*(p-a)*(p-b)*(p-c))
print(s)
elif n == 7.2:
print(round (math.pi,2))
elif n == 7.3:
x=int(input('Введите x'))
print(math.sqrt(1-(pow(math.sin(... |
import numpy as np
list1 = list(range(1000))
get_ipython().magic('timeit newlist = [i + 2 for i in list1]')
arr1 = np.array(list1)
get_ipython().magic('timeit newlist = arr1 + 2')
from random import random
list2 = [random() for i in range(10000)]
get_ipython().magic('timeit min(lis... |
import random
def get_guess():
return list(input('Enter 3 Digit Code'))
def code_generator():
digits = [str(num) for num in range(10)]
random.shuffle(digits)
return digits[:3]
def generate_clues(code,user_guess):
if user_guess == code:
return 'Attaboy! Code Cracked'
... |
from .card import NumberCard
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
YELLOW = 'yellow'
DRAW_CARD_INPUT = ''
EXIT = 'exit'
ASK_FOR_INPUT = \
"Please select index of card to play! \n" + \
"Or just press enter to draw a card \n" + \
"(Type exit to quit) \n"
UNO_FINAL_LAST_PLAYED_CARD = NumberCard('red', 7)
U... |
num1 = 4
num2 = 4
result = num1 + num2
print(result)
num1 = int(input('enter the firExamst number:'))
num2 = int(input('enter the second number:'))
result = num1 + num2
print('your answer is:', result)
num1 = int(input('Enter number 1:'))
num2 = int(input('Enter number 2:'))
result = num1 + num2
print(result)
... |
import collections.abc
class OrderedSet(collections.abc.MutableSet):
"A set that maintains insertion order"
def __init__(self):
self._data = {}
def add(self, item):
if item not in self:
self._data[item] = 1
def discard(self, item):
if item in sel... |
class Transport:
def __init__(self):
self.value = 0
self.speed = 0
self.year = 0
self.coord = ""
def setVal(self, input):
self.value = input
def setSpeed(self, input):
self.speed = input
def setYear(self, input):
self.year = input
... |
import random
history = []
def welcome():
print(
"""
____________________________________
Welcome to the Number Guessing Game!
____________________________________
""")
def start_game():
another = "y"
solution = random.randint(1,10)
value = "Oh no! That's not a valid value. Pl... |
from turtle import *
def rectangle(points):
[[x0,y0],[x1,y1],[x2,y2],[x3,y3]] = points
up()
setpos(x0,y0)
down()
setpos(x1,y1)
setpos(x2,y2)
setpos(x3,y3)
setpos(x0,y0)
def deviding_point(p0,p1,ratio):
[x0,y0] = p0
[x1,y1] = p1
xr = deviding(x0,x1,ratio)
yr ... |
print ("Libby's Calculator!")
a=input("Please input A:")
b=input("Please input B:")
a=int(a)
b=int(b)
print("A+B=",a+b)
print("A*B=",a*b)
print("A/B=",a/b)
print("A-B=",a-b)
print("A**B=",a**b)
if a>b:
print("A is larger than B.")
if a<b:
print("A is smaller t```han B.")
if a==b:
print("A is equal to B.")... |
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame, text="Button 1", fg="red", command="hello")
button2 = Button(topFrame, text="Button 2", fg="blue")
button3 = Button(topFrame, text="Button 3", fg="green")
but... |
import matplotlib.pyplot as plt
import numpy as np
get_ipython().run_line_magic('matplotlib', 'inline')
x=np.linspace(0,2*np.pi,360)
y1=np.sin(x)
y2=np.sin(x**2)
plt.plot(x,y1,label='sin(x)')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine-Wave!')
f, ax=plt.subplots()
ax.pl... |
class Compute:
def __init__(self):
self.l = []
def add(self,a=0):
if a == 0:
a = self.get_val()
self.l.append(a)
print('List : ',self.l)
def remove(self,a=0):
print('List : ',self.l)
if a == 0:
a = self.get_val()
sel... |
import random
import time
class Problem7:
def printrandom(self):
for i in range(10):
print(random.randint(1,100))
time.sleep(random.randint(0,1))
def problem7(self):
starttime = time.time()
self.printrandom()
endtime = time.time()
print('Total elaps... |
from math import sqrt,floor
def SieveOfEratosthenes(prime,n):
p=2
x=[]
while(p * p <= n):
if (prime[p] == True):
x.append(p)
for i in range(p * 2, n+1, p):
prime[i] = False
p+=1
lis =[]
... |
from nltk import word_tokenize
from nltk.corpus import stopwords
import string
s = []
while True:
sent = input()
if sent is None:
break
stop = stopwords.words('english') + list(string.punctuation)
s+=[i for i in word_tokenize(sent.lower()) if i not in stop]
print(s) |
wordinput = input("Please Type In A Word: ")
reverseword = ''
for x in range(len(wordinput)-1, -1, -1):
reverseword = reverseword + wordinput[x]
print(reverseword)
if wordinput == reverseword:
print("This is a palindrome!")
else:
print("This is not a palindrome:(")
print("Ta-Da!")
... |
if __name__ == '__main__':
n = int(input())
outputstring = ''
for x in range(1, n + 1):
outputstring = outputstring + str(x)
print(outputstring)
|
string = "abcdefghijklmnopqrstuvwxyz"
print("-"+"\t"+"0")
for i in range(len(string)):
print(string[i]+"\t"+str(i+1))
|
import sys
fileName = sys.argv[1]
f = open(fileName, "r")
fline = f.readlines()
for i in range(len(fline)):
line1 = fline[i].split(" ")
if i < len(fline) - 1:
start = i + 1
for j in range(start,len(fline)):
line2 = fline[j].split(" ")
for k in range(len(line1)):
for m in range(len(line2)):
... |
import numpy as np
arr = np.array([2,4,2,9,2])
print("Array: ",arr)
x = [False, False, True, False, True]
newarr = arr[x]
print("Filtered new array : ",newarr)
arr = np.array([100, 110, 120, 150, 180])
filterarr = []
for e in arr:
if e < 150:
filterarr.append(True)
else:
filterarr... |
x = int(input('Pick a number between 2 and 10'))
if x == 1 or x > 10:
print('That is not what I asked.')
else:
print('Please hold while I calculate...')
while x < 10:
x += 1
print (str(x) + ' ...')
|
import numpy as np
def ortho(m):
identity_m = np.identity(m.shape[0])
return np.allclose(np.matmul(m, m.T).flatten(), identity_m.flatten())
def main():
d = np.array([[2, 2, -1], [2, -1, 2], [-1, 2, 2]])/3
if ortho(d):
print('matrix', d, 'is orthogonal')
else:
print('matrix', d, 'is not orthogonal')
if __na... |
""" Qiu Zihao's homework of ML
Student ID: 141130077
Neural Network
"""
import numpy as np
input_num = 400
hidden_num = 100
output_num = 10
v = (np.random.random(size=(input_num, hidden_num))-0.5)/10
w = (np.random.random(size=(hidden_num, output_num))-0.5)/10
gama = np.zeros([1, hidden_num])
theta = np... |
txt1 = 'A tale that was not right'
txt2 = '이것 또한 지나가리라'
print(txt1[5])
print(txt2[-2])
print(txt1[3:7])
print(txt1[:6])
print(txt2[-4:])
txt = 'python'
for i in range(len(txt)):
print(txt[:i+1])
txt = 'aAbBcCdDeEfFgGhHiIjJkKlLmMn... |
import csv
import os
filename = 'test_write.csv'
csv_path = os.getcwd() + '\\csv_files\\' + filename
header_data = ["1行号", "2列名1", "3列名2"]
row_data = [1, '第1列数据', '第2列数据']
with open(csv_path, "w", encoding='utf8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(row_data)
... |
def color_nodes(graph):
nodes = sorted(list(graph.keys()), key=lambda x: len(graph[x]), reverse=True)
color_map = {}
for node in nodes:
available_colors = [True] * len(nodes)
for neighbor in graph[node]:
if neighbor in color_map:
color = color_map[neighbor]
available_colors[col... |
INPUT_ERROR_INT = 'Must be an integer. Try again.'
INPUT_ERROR_STR = 'Must be either K, C, R, F. Try again.'
def input_num(message):
while True:
try:
user_input = int(input(message))
except ValueError:
print(INPUT_ERROR_INT)
continue
else:
r... |
"""
Task 6.2a
Make a copy of the code from the task 6.2.
Add verification of the entered IP address.
An IP address is considered correct if it:
- consists of 4 numbers (not letters or other symbols)
- numbers are separated by a dot
- every number in the range from 0 to 255
If the IP address is incorrect... |
"""
Task 5.1
The task contains a dictionary with information about different devices.
In the task you need: ask the user to enter the device name (r1, r2 or sw1).
Print information about the corresponding device to standard output
(information will be in the form of a dictionary).
An example of script execution:
$ ... |
""" Math Tools
Some general math tools that can help with numbers)
"""
import math
import random
def EGCD(a, b):
"""
Extended Euclidean algorithm
computes common divisor of integers a and b.
a * x + b * y = gcd(a, b)
returns gcd, x, y or gcd, y, x.
Sorry, I can't remembe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.