text stringlengths 37 1.41M |
|---|
import numpy as np
def activation(x):
if x > 1:
f = 1
else:
f = 0
return f
def perceptron(X,d,alfa=0.05,max_it=100):
X = np.insert(X,0,1,axis=1)
W = np.zeros(X.shape[1])
t = 1
E = 1
N = X.shape[0]
y = np.zeros(N)
while t < max_it and E > ... |
import os as os
def main():
currentDir = os.path.dirname(os.path.realpath(__file__))
os.chdir(currentDir)
os.chdir('..')
stopwordsList = open('data/stopwords.txt', 'r')
#stopwordsList = open('data\stopwords.txt', 'r')
stopwordsList = stopwordsList.read().splitlines()
userInput = input()
... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
def findStockInformation(url):
request = urlopen(url)
html_page = request.read()
request.close()
page_soup = BeautifulSoup(html_page, "html.parser")
block = page_soup.find("div", {"class":"stock-overview__text-and-value-items"})
... |
# Python program for MergeSort
a = [19, 56, 59, 26, 34, 12, 3, 97]
def mergeSort(a):
if len(a) > 1:
mid = len(a)//2
l = a[:mid]
r = a[mid:]
mergeSort(l)
mergeSort(r)
i = j = k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
... |
#Dylan Rich Lab 1C 1/13/20
def capacity():
cap=int(input("How many people can fit in the room?"))
return cap
def attendees():
people=int(input("How many people are going to attend?"))
return people
def register(x,y):
difference=x-y
return difference
def another():
answer1=input("Would you li... |
from bs4 import BeautifulSoup
import json
import sys
import urllib
import urllib2
# Max number of pages to click through when scraping reviews
MAX_PAGES_TO_SCRAPE = 5
# Google Play Reviews API base URL
# Give it a try:
# curl --data \
# "reviewType=0&pageNum=15&id=com.inxile.BardTale&reviewSortOrder=2&xhr=1" \
# ... |
class Node():
def __init__(self):
self.children = {}
self.value = None
class Trie():
def __init__(self, strings, values):
self.root = Node()
for index, string in enumerate(strings):
self.insert(string, values[index])
def find(self, string):
node... |
# Main file that creates a number of important objects throughout the game.
import pygame
from pygame.sprite import Group
from settings import Settings # imports settings into the main program
from game_stats import GameStats
from scoreboard import Scoreboard
from button import Button
from ship import Ship
import ga... |
__author__ = 'smelnyk'
# from itertools import groupby
import re
"""
Today, the Elves are playing a game called look-and-say.
They take turns making sequences by reading aloud the previous sequence and
using that reading as the next sequence.
For example:
211 is read as "one two, two ones", which becomes 1221 (1 2, ... |
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import numpy as np
#finding the best value of K with the use of KNeighborsClassifier
breast_cancer_data = load_breast_cancer()
training... |
#!/usr/bin/python
__author__ = 'jdr0dn3y'
import urllib2
import json
import requests
btcurl = 'https://btc-e.com/api/2/btc_usd/ticker'
btcltcurl = 'https://btc-e.com/api/2/ltc_btc/ticker'
ltcurl = 'https://btc-e.com/api/2/ltc_usd/ticker'
#Enter the number of *coins you have
btcowned = 1
ltcowned = 1
def parse(jso... |
import module
Simvol = input("Введите символ ожидаемой операции (+, -, /, *, ^, m(модуль), r(рандомное число), f(факторил), a(арккосинус): ")
if Simvol == "+":
module.plus()
elif Simvol == "-":
module.minus()
elif Simvol == "/":
module.delenie()
elif Simvol == "*":
module.umn()
elif Simvol == "^":
... |
from math import pi
while True:
Data = float(input("ENTER A NUMBER OF YOUR CHOOSE: "))
print("THE AREA OF A CIRCLE : "+str(Data)+ " is: " + str (pi * Data**2))
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from recognizers_date_time import recognize_datetime
from recognizers_text import Culture
class Ranges:
"""
TIMEX expressions can represent date and time ranges. Here are a couple of examples.
"""
@staticme... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datatypes_timex_expression import Timex, Constants
class Parsing:
"""
The Timex class takes a TIMEX expression as a string argument in its constructor.
This pulls all the component parts of the expression i... |
#LZW compression and Decompression
#MKChaudhary
#26nov'19
print("encoding")
string=raw_input("enter string to compress:-")
codes = dict([(chr(x), x) for x in range(256)])
compressed_data = []
code_count = 257
current_string = ""
for c in string:
current_string = current_string + c
if current_string not i... |
a =[]
for i in range(5):
i = float(input())
a.append(i)
for i in range(len(a)):
a[i] = a[i] * a[i]
print('Tavan 2 Majmoe barabar ast ba:')
print(a)
print('Min va Max Majmome')
print(min(a))
print(max(a))
|
mat1=[]
mat2=[]
mattemp=[]
cpy=[]
var = 0
a = 0
b = 0
while a<3:
while b<3:
var = int(input('enter number'))
mattemp.append(var)
b+=1
cpy = mattemp.copy()
mat1.append(cpy)
mattemp.clear()
a+=1
b=0
a=0
while a<3:
while b<3:
var = int(input('... |
s1=int(input('enter a number: '))
s2=int(input('enter a number: '))
if s1>s2:
print ('%d greater'%s1) #old method
elif s2>s1:
print ('%d greater'%s2) #old method
else:
print('both are equal')
... |
a=5
b=10
c = a+b
d=a-b
e=a*b
f=a/b
g=a**b #square
h=a//b #div without float answer
i=a%b
print (c)
print (d)
print (e)
print (f)
print (g)
print (h)
print (i)
|
l=[1,4,3,2,5,3,6,5,2,7,4,2,3,5,4]
l2=[]
s=set(l)
l1=list(s)
print('without duplicate ascending order',l1)
l1.reverse()
print('without duplicate decending order',l1)
|
class A:
a=20
b=40
def multi(self):
print(self.a*self.b)
class B(A):
x=20
y=20
def add(self):
print(self.x+self.y)
class C(B):
s=1
def check(self):
print(self.s)
k=C()
k.add()
k.multi()
|
s=int(input('enter a number: '))
if s%2: #trucy and falsy value or negated o/p
print ('%d is a odd number'%s) #old method
# print ('is a positive number')
else:
print('its even number')
|
mat1=[[1,2,3],[2,3,4],[5,4,3]]
mat2=[[8,6,2],[1,3,7],[4,3,1]]
res=[]
res2=[]
temp=[]
add=0
i=0
while i<3:
j=0
while j<3:
add = mat1[i][j] + mat2[i][j]
res.append(add)
j+=1
temp=res.copy()
res2.append(temp)
res = []
i+=1
print(res2)
|
class temp():
x=10
y=20
def default(self):
print(self.x,self.y)
# obj=temp()
# print(obj.x)
# print(obj.y)
obj=temp()
obj.default()
|
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
# Begin appending index at 0
self.ind = 0
# Create empty list to store items
self.items = []
def append(self, item):
# First check if index needs to be reset to not exceed capacity
i... |
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=news")
def execute(has_commit, query, *params):
"""
Connects to the PostgreSQL database, executes the query and returns
the rows, if any.
"""
db = conn... |
import pickle
class Save_Load_Model:
'''For saving and loading model'''
def __init__(self, folderPath = None):
'''Take path to the folder for saving and loading model as an argement. Default is 'saved _models'''
if folderPath is None:
print("Please, provide path to folder.")
exit(0)
else:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pyChallenge_3.py
#
import string
import re
import urllib.request
def getHtml(url):
# 获得网页源码
page = urllib.request.urlopen(url)
html = page.read()
return html
def getStr(html):
# 从源码中获取所需字符串 http://www.jb51.net/article/20654.htm
reg = r'not... |
from math import *
from graphics import *
# Dylan Wise
# Section 001
# 10/6/13
# Write the definition of a function called distance
# with the parameters of 2 points
# which returns the distance between the two points
# you may NOT use the distance method which exists
def distance (pt1, pt2):
a = pt1.getX() ... |
#!/usr/bin/env python
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
__author__ = "Alex Comiskey"
#Check whether number is divisible by all number is ... |
#!/usr/bin/env python
""""
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers
"""
__author__ = "Alex Comiskey"
with open("num_13.txt", "r") as f:
nums = [int(x.strip('\n')) for x in f.readlines()]
num_sum = str(sum(nums))
print(num_sum[0:10])
|
"""
This script shows how to build a simple tensorflow graph and how to run it in a session to calculate the sum of 2 numbers.
"""
import tensorflow as tf
graph = tf.Graph()
with graph.as_default():
a = tf.placeholder(dtype=tf.int32, shape=[1])
b = tf.placeholder(dtype=tf.int32, shape=[1])
sum_ab = tf.add... |
"""
------------------------
Quicksort implementation
------------------------
Worst case complexity: O(n^2)
pseudo code: Introduction to Algorithms 3rd edition
"""
def partition(a, l, r):
""" Pivot is the first element of the list."""
pivot = a[l]
index = l
for i in range(l + 1, r... |
class OS:
multitasking=True
name="Mac Os"
class Apple:
website='www.apple.com'
name="Apple"
class MacBook(OS,Apple):
def __init__(self):
if self.multitasking is True:
print('Hi, this is made by {}'.format(self.website))
print(self.name)
#order d... |
class Square:
def __init__(self,side):
self.side=side
def __add__(squareOne,squareTwo):
return (4*squareOne.side+4*squareTwo.side)
squareOne=Square(5)
squareTwo=Square(10)
print('Sum of Squares:',squareOne+squareTwo)
|
# ch10_2.py
fruits1 = ['apple', 'orange', 'apple', 'banana', 'orange']
x = set(fruits1) # 將串列轉成集合
fruits2 = list(x) # 將集合轉成串列
print("原先串列資料fruits1 = ", fruits1)
print("新的串列資料fruits2 = ", fruits2)
|
# ch8_13.py
drinks = ["coffee", "tea", "wine"]
enumerate_drinks = enumerate(drinks) # 數值初始是0
lst = list(enumerate_drinks)
print("轉成串列輸出, 初始索引值是 0 = ", lst)
print(type(lst[0]))
|
# ch11_25_7.py
def outer():
b = 10 # inner所使用的變數值
def inner(x):
return 5 * x + b # 引用第3行的b
return inner
b = 2
f = outer()
print(f(b))
|
# ch31_10.py
import turtle
t = turtle.Pen()
sides = 5 # 星星的個數
angle = 180 - (180 / sides) # 每個迴圈海龜轉動角度
size = 100 # 星星長度
t.color('blue')
t.begin_fill()
for x in range(sides):
t.forward(size) # 海龜向前繪線移動100
t.right(angle) # 海龜方向左轉的度... |
# ch30_26.py
import threading, time, random, queue
bufSize = 10
q = queue.Queue(bufSize) # 建立queue,最多10筆
def producer(): # 生產者狀況
while True:
if not q.full(): # 如果queue有空間
... |
# ch12_9_3.py
class Score():
def __init__(self, score):
self.__score = score
def getscore(self):
print("inside the getscore")
return self.__score
def setscore(self, score):
print("inside the setscore")
self.__score = score
sc = property(getscore, setscor... |
# ch30_25.py
import threading, time, random
def producer(): # 生產者狀況
while True:
condition.acquire() # 鎖定
if len(data) >= 5: # 如果產品滿了
print("生產線是 waiting ...") ... |
# ch6_56.py
drinks = ["coffee", "tea", "wine"]
enumerate_drinks = enumerate(drinks) # 數值初始是0
print(enumerate_drinks) # 傳回enumerate物件所在記憶體
print("下列是輸出enumerate物件類型")
print(type(enumerate_drinks)) # 列出物件類型
|
# ch12_11_1.py
class Person():
def __init__(self,name):
self.name = name
class LawerPerson(Person):
def __init__(self,name):
self.name = name + "律師"
hung = Person("洪錦魁")
lawer = LawerPerson("洪錦魁")
print(hung.name)
print(lawer.name)
|
# ch7_39.py
fruits = ['apple', 'orange', 'apple', 'banana', 'apple']
fruit = 'apple'
print("刪除前的fruits", fruits)
while fruit in fruits: # 只要串列內有apple迴圈就繼續
fruits.remove(fruit)
print("刪除後的fruits", fruits)
|
# ch12_22.py
def getMax(x, y):
'''文件字串實例
建議x, y是整數
這個函數將傳回較大值'''
if int(x) > int(y):
return x
else:
return y
print(getMax(2, 3)) # 列印較大值
print(getMax.__doc__) # 列印文件字串docstring
|
# ch6_53.py
x = 10
y = 10
z = 15
r = 20
print("x = %d, y = %d, z = %d, r = %d" % (x, y, z, r))
print(f"x位址 = {id(x)}, y位址 = {id(y)}, z位址 = {id(z)}, r位址 = {id(r)}")
r = x # r的值將變為10
print(f"{x = }, {y = }, {z = }, {r = }")
print(f"x位址 = {id(x)}, y位址 = {id(y)}, z位址 = {id(z)}, r位址 = ... |
# ch31_9.py
import turtle
t = turtle.Pen()
t.color('white')
r = 30 # 半徑
t.penup()
t.setheading(180) # 海龜往左
t.forward(270) # 移動往左
t.setheading(0) # 海龜往右
colorsList = ['red','orange','yellow','green','blue','cyan','purple',... |
# ch10_31.py
cocktail = {
'Blue Hawaiian':{'Rum','Sweet Wine','Cream','Pineapple Juice','Lemon Juice'},
'Ginger Mojito':{'Rum','Ginger','Mint Leaves','Lime Juice','Ginger Soda'},
'New Yorker':{'Whiskey','Red Wine','Lemon Juice','Sugar Syrup'},
'Bloody Mary':{'Vodka','Lemon Juice','Tomato Juice','Ta... |
# ch31_8.py
import turtle
t = turtle.Pen()
t.color('blue')
r = 30 # 半徑
t.penup()
t.setheading(180) # 海龜往左
t.forward(270) # 移動往左
t.setheading(0) # 海龜往右
for edge in range(3, 13, 1): # 繪3 - 12邊圖
t.pendown()
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 5 00:35:05 2016
@author: Damien Robinson
"""
def dotProduct(listA, listB):
'''
listA: a list of numbers
listB: a list of numbers of the same length as listA
returns the sum of the pairwise products of listA and listB.
'''
result = 0
for index... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 30 22:37:49 2016
@author: Damien Robinson
"""
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
num = 0
for key in aDict.keys():
num += len(aDict[key])
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 14 20:08:37 2016
@author: Damien Robinson
"""
from math import *
def polysum(n, s):
'''
n: number of sides
s: side length
returns: sum of the area and square of the perimeter of the regular
polygon rounded to 4 decimal places.
'''
#cal... |
import Queue as Cola
class Cajero():
def __init__(self):
self.disponible = True
self.cola_clientes = Cola.Queue()
self.tiempo_servicio = 0
self.tiempo_servicio_total = 0
self.recien_asignado = False
self.cliente_atendido = None
@staticmethod
def tie... |
class Queue():
'''using double-linked list to implement a queue'''
class __Node():
'''inner class as double-linked list node'''
def __init__(self, key = None, pre = None, next = None):
self.key = key
self.pre = pre
self.next = next
def __init__(self):
... |
def topo_sort(graph):
queue = []
for x in graph:
if graph[x]["indegree"] == 0:
queue.append(x)#首先将孤立的点都加入队列中
order_list = []
while len(order_list) != len(graph):#如果没有将所有顶点排完序
cur = queue.pop(0)
order_list.append(cur)
#每添加完一个新的顶点,将该顶点的所有邻接顶点入度都减1
for x... |
class Node():#定义节点
"""docstring for Node"""
def __init__(self, key, next = None):
self.key = key#元素
self.next = next#下一个元素的引用
def insert(head, key):
'''插入新的元素, 头插法'''
newOne = Node(key, head.next)
head.next = newOne
def search(head, key):
'''搜索链表是否包含某个元素'''
while head and h... |
topo_order = []#保存拓扑顺序
visited = {}#标记是否被访问
def dfs(graph, start):
for x in graph[start]:
if visited[x] == False:
visited[x] = True
dfs(graph, start)
topo_order.insert(0, start)#添加排序顶点到列表
def topo_sort(graph):
for x in graph:
if visited[x] == False:
visi... |
#http://www.smartoj.com/p/1006
website = ["http://www.acm.org"]
index = 0
while True:
cmd = list(map(str, input().strip().split()))
if len(cmd) == 2:#覆盖当前下标的下一个位置
print(cmd[1])
index += 1
if index >= len(website):
website.append(cmd[1])
else:
website[index... |
# function
# parameters
def greet_user(name, age):
print(f"what's up {name}? your age: {age}")
print("learning python is fine!")
# keyword args
print("Start")
greet_user(age=13, name="James")
greet_user(name="Neo", age=23)
print("done")
def square(number):
return number * number
print(square(3))
|
valorReal = float(input("Insira o valor em real:"))
valorDolar = (valorReal * 0.18)
print("O valor",(valorReal),"R$ em dólares é:",(valorDolar),"U$") |
import math
import exceptions
__all__ = [
'Angle',
'Dec_angle',
'Hour_angle',
'RA_angle',
'Deg10',
'delimError',
'parseError'
]
class Angle():
"""Class to handle different types of astronomical angles
args: rawval, type, delim
Desc: Takes rawval and converts it to rotations leavi... |
sports = summer_2016_medals["Sport"].unique()
print(sports) // This gives the unique items in the Sport column
fig, ax = subplots()
for sport in sports:
sport_df = summer_2016_medals[summer_2016_medals["Sport"] == sport]
ax.bar(sport, sport_df["Height"].mean(),
yerr = sport_df["Height"].std())
a... |
m=int(input())
fact=1
if(m<=20):
while(m>0):
fact=fact*m
m=m-1
print(fact)
|
a=int(input())
num=0
while(a>0):
a//10
num=num+1
print(num)
|
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline,interp1d
# given values
xi = np.array([0.2, 0.5, 0.7, 0.9])
yi = np.array([0.3, -0.1, 0.2, 0.1])
# positions to inter/extrapolate
x = np.linspace(0, 1, 50)
# spline order: 1 linear, 2 quadratic, 3 cub... |
class Prueba( object ):
def __init__( self ):
self.__privado = "Soy Privado"
self.publico = "Sou Público"
def __privado( self ):
print( "Soy privado" )
def publico( self ):
print( "Soy Público" )
def getPrivado( self ):
return self.__privado
obj = Prueba()
#print( obj.publico )
#print( obj.__pri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 2 19:46:09 2019
@author: shubham
"""
import pandas as pd
import numpy as np
class Feature_Prepration:
"""
This is a class for Feature prepration in order to deal with
outliers and missing values.
Attributes:
... |
# -*- coding: utf-8 -*-
name_list=["alex","steven","eric"]
name_list2=list(["alex2","steven2","eric2"])
print(name_list)
num = name_list.index("steven")
print(num)
name_list.insert(5,"ffff")
name_list.insert(len(name_list),"jjj")
name_list.remove("alex")
print(name_list)
print(name_list.pop(1))
print(name_list)
print(... |
from Unittest import TestCase
items = [0, 1, 2]
new_items = map(lambda x: x + 1, items)
new_items2 = [x+1 for x in items]
# e ::= v variable
# | e(e) application
# | lambda v: e abstraction
zero = lambda f : lambda x : x
succ = lambda a : lambda f : lambda x : f(a(f)(x))
add = lambda a : lambda ... |
def comp(array1, array2):
if not array1 or not array2:
return False
if len(array1) != len(array2):
return False
while(array1):
for j,y in enumerate(array2):
if array1[0]**2 == y:
array1.pop(0)
array2.pop(j)
bob = len(array2)
... |
# For in range
for i in range(3):
print(i)
print('\n')
# For in range <start, end>
for i in range(1, 5):
print(i)
print('\n')
# For i in range with 2 sequence
for i in range(1, 10, 2):
print(i)
print('\n')
# The else keyword in for loop specifies a block of code to be executed when the loop is finishe... |
'''
a strong number is defined as a number that has the sum of the factorial of
each digit is equal to its original number
print("please enter a number that might be strong")
snumber = input(">")
'''
for n in range(10000001):
snumber = str(n)
#get all of the digits (split)
digits = list(snu... |
numbers = input("enter 10 numbers with a comma inbetween")
print(numbers)
numbers_list = numbers.split("comma")
numbers_count = len(numbers_list)
half = int(numbers_count/2)
print(numbers_list)
last_half = numbers_list[half:numbers_count]
print(last_half)
first_half = numbers_list[0:half]
print(first_h... |
#Ask the user how many times they want to count
#Change the code to count to that value
#display a square that is length & height of that number of times
'''
first display a line with that number of stars
****
display a square with the number of stars
****
****
****
****
***
***
***
'''
t... |
def a(list_num):
list_num[0] +=1
print(list_num[0])
def a1(b):
a(b)
a(b)
def a2(b):
a1(b)
a1(b)
def a3(b):
a2(b)
a2(b)
x = [0]
a3(x)
print(x)
|
'''
problem 1
Ask a user for a number. Depending on the number, respond with how many factors exist within that number
for example:
Enter a number
>15
15 has 4 factors, which are 1 3 5 15
'''
'''
problem 2
Write a program that will ask a user for a word. For that word, replace each letter wi... |
def hi(name):
print('hello' + name)
girls = ['yoonseo','jenny','jiny']
for name in girls:
hi(name)
for a in range(1,6):
print(a)
i=0
while i<5:
print(i)
i+=1 |
import cv2 #lines 1-13 follow standrd procedure of importing packages, parsing arguments, and loading the image
import argparse
import imutils
#flipping --> can flip an image around on the x or y axis, or both
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to the image")... |
#there are many more color spaces than RGB
#e.g. the HSV color space is more similar to how humans conceive of color
#OpenCV provides support for many of these color spaces
import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to th... |
#blurring = each pixel in the image is mixed in with surrounding pixel intensities
import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])#loading image and s... |
"""
Carlos Redondo
December 11th, 2017
"""
"""
BASICS
Obtain how many passphares are valid.
"""
"""
PART 1
"""
# A passphrase is considered valid if it has the same length than a set with
# no repeated elements
Nonrep1 = 0 # Final result
# Reads the file, skipping the empty lines
with open('A4data.txt') as f_in... |
from board import Board
from btree import Btree
class Player:
def input_prompt(self):
while True:
inp = input("Please enter number of row and column, separated by space: ")
try:
row, col = int(inp.split(' ')[0]) -1 , int(inp.split(' ')[1]) -1
except (Va... |
qtd_heapify = 0
swaps = 0
def heapify(v, n, i):
global qtd_heapify
qtd_heapify += 1
menor = i # Inicializa menor como raiz
left = 2 * i + 1
right = 2 * i + 2
# Veririfca se o filho da esquerda da raiz existe e
# se é menor que a raíz
if left < n and v[i] > v[left]:
m... |
#
# ps9pr2.py (Problem Set 9, Problem 2)
#
# A Connect-Four Player class
#
from ps9pr1 import Board
# write your class below
class Player:
"""a data type to be able to like actually play the game w someone"""
def __init__(self, checker):
"""initializes attribute checker and num moves"""
... |
"""
profiling_decorator.py - defines a decorator for profiling function
execution time
Usage example:
@profile_call
def my_func(a, b, c):
...
"""
from time import process_time
from decorators import format_args
def profile_call(decorated_fn):
"""decorator for profiling function execution time"""... |
"""debugging_demo.py - Example of debugging from chapter 4"""
class DebuggingDemo(object):
def __init__(self, name, num_loops):
self._name = name
self._count = num_loops
def count(self):
for i in range(self._count):
print(i)
return '{} executed {} of {} loops'\
... |
n=int(input("Enter a number: "))
primes=[]
count=0
for i in range (3,n+1):
flag=0
for j in range (2,i):
if(i%j==0):
flag=1
if(flag==0):
primes.append(i)
print(primes)
for prime in primes:
sum=2
for i in range (3,prime):
f=0
for j in range (2,i):
... |
# -*- coding: utf-8 -*-
import tkinter
from random import randint
step = 20
speed = 300
speed_level = 7
speed_step = 25
width, height = 640, 480
x_coef = int(width / step) - 1
y_coef = int(height / step) - 1
border = int(step / 10)
sneak_body = [(12, 16), (12, 17), (12, 18)]
x_a, y_a = 1, 0
x_head, y_head = sneak_bod... |
import string
alph = string.ascii_lowercase
message = 'It is an encrypted message'
step = 10
new_message = ""
for el in message:
if el == " ":
el = el
new_message += el
elif ord(el) + step > ord('z'):
new_message += chr(ord(el) + step - 26)
else:
new_message += chr(ord(el) + step)
print(new_message)
|
import pygame.font
class Button():
"""Класс кнопки Play"""
def __init__(self, screen):
"""Инициализирует аттрибуты кнопки"""
self.screen = screen
self.screen_rect = screen.get_rect()
# Назначение размеров и свойств кнопок
self.width, self.height = 125, 50
self... |
# Вводим число
n = int(input("Number n: "))
a = 1
for _ in range(2, n):
a += _
print(a)
|
list1 = input("Введите через пробел элементы первого списка: ")
list2 = input("Введите через пробел элементы второго списка: ")
# Преобразуем строки в списки
list1 = list(list1.split())
list2 = list(list2.split())
# Сортируем списки и сравниваем их
if sorted(list1) == sorted(list2):
print('Списки равны')
else:
... |
dict1 = {'1': 'one', '2': 'two', 'hi': 'привет',
'no': 'нет', 'yes': 'да'}
# Вводим ключ
key_input = input('Input key of dictionary: ')
# Выводим значение по ключу
print(dict1.get(key_input, "Empty"))
|
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Добавляем второй список с помощью метода extend
list1.extend(list2)
print(list1)
|
import matplotlib.pyplot as plt
import numpy as np
import math
x0 = 5
def get_n_element(x0, r, n):
f = lambda x: x*math.exp(r*(1-x))
last = f(x0)
for i in range(1, n):
last = f(last)
return last
r = np.concatenate((np.linspace(0, 3, 1000), np.linspace(3, 3.5, 1000)))
last = get_n_... |
from CrowdFunding import registration
from CrowdFunding import login
def main_menu():
while True:
print("-------- Main Menu ----------")
choice = int(input("""
1: Register
2- LogIn
3- Exit
"""))
if choice == 1:
registration.register()
e... |
"""
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finish... |
"""
n! means n x (n - 1) x ... x 3 x 3 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
bigNumber = 1
bigNumberSum = 0
for i in xrange (1, 101):
bigNumber *= i
while bigNum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.