text stringlengths 37 1.41M |
|---|
import numpy as np
import sys
import argparse
import os
import json
import re
import csv
def extract1( comment ):
''' This function extracts features from a single comment
Parameters:
comment : string, the body of a comment (after preprocessing)
Returns:
feats : numpy Array, a 173-length ... |
import time
class Stopwatch:
def __init__(self):
self.start_time = None
self.end_time = None
self.speed = 1
self.interval = 0
def start(self, speed=1):
if self.start_time is None:
self.start_time = time.time()
self.speed = speed
elif sel... |
"""
Simple program that generates a random text file
Allows user to enter the amount of lines in the text file, and
the amount of characters per line
Allows user to specify whether they want to include all letters, or allow
numbers, special characters, etc
By default saves program to the directory where the python fil... |
#-------------------------------------------------------------------------------
# Name: Player class
# Purpose:
#
# Author: Osnovnoy
#
# Created: 15/11/2016
# Copyright: (c) Osnovnoy 2016
# Licence: <your licence>
#-------------------------------------------------------------------------... |
##import the module random
import random
##DICES
##returns a random integer between (1,6) x2
dice1=random.randint(1,6)
dice1=int(dice1)
dice2=random.randint(1,6)
dice2=int(dice2)
dice=int(dice1)+int(dice2)
##TOTAL NUMBER OF PLAYS
i=0
##GAME STARTS HERE
##user input roll
roll=input("Welcome to Craps! Type ROLL to beg... |
# First off, let's import the libraries we require to make the whole process
import urllib.parse, urllib.request, urllib.error
import json
import ssl
# I am ignoring any certificate errors with this
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Here I aim to obtain t... |
# This program will extract all the number in this document, and compute a sum at the end.
# I use regular expressions, "for" loops, and conditionals to accomplish this.
import re
hand = open("regex_sum_265510.txt")
accum = list()
accum2 = list()
sigma = 0
for line in hand :
line.strip()
line = re.findall('[0-9... |
import string
from collections import deque
def calculate(expression): # evaluates and calculates an expression
postfix_ex = convert_infix_post(expression)
operand_stack = deque()
for term in postfix_ex:
if str(term) in operators:
ope2 = operand_stack.pop()
ope1 ... |
import random
import os
import time
os.system("color")
# colour escape code
green = "\033[5;32;40m"
red = "\033[1;31;40m"
yellow = "\033[1;33;40m"
# functions
def question_check(question, answer_list, error_message):
valid = False
while not valid:
response = input(question).lower().strip()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def input():
return sys.stdin.readline()
def dfs_four_number(s_num, i, op_list:list):
# ベースケース
if i == 3:
ans_num = int(s_num[0])
for j, op in enumerate(op_list):
if op == "+":
ans_num += int(s_num[j+1])... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = input()
if len(s) == 0:
print('No')
exit()
for i, letter in enumerate(s):
if i % 2 == 0:
if letter != 'h':
print('No')
exit()
elif i % 2 != 0:
if letter != 'i':
print('No')
exit()
if len... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def bit_and(a: int, b: int):
bin_a = bin(a)
bin_b = bin(b)
print("{} and {} = {}".format(a, b, a & b))
print("{} and {} = {}".format(bin_a, bin_b, bin(a & b)))
def bit_or(a: int, b: int):
bin_a = bin(a)
bin_b = bin(b)
print("{} or {} = {}".f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = input()
s_length = len(s)
print("x" * s_length)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 入力
n = int(input())
a = list(map(int, input().split()))
# 変数
alice_score = 0
bob_score = 0
# ソート
a = sorted(a, reverse=True)
# 0から始まるので偶数が有栖の手番になる
for i, ai in enumerate(a):
# アリスの手番
if i%2 == 0:
alice_score += ai
# ボブの手番
elif i%2 != 0:
... |
class Player:
def __init__(self, name, colour):
self.name = name
self.colour = colour
class PlayerSetup:
ACCEPTABLE_ANSWERS = {'y', 'yes', '1'}
def __init__(self, player_1 = Player('Player 1', 'RED'), player_2 = Player('Player 2', 'GREEN')):
self.player_1 = player_1
self.player_2 = player_2
self.run()
... |
name= input("Enter your name: ")
Reg= input("Enter your ID number: ")
print("Name is {0} and ID is {1}".format(name,Reg)) |
import Trips
from time import time
minutes = int(raw_input("Window size (minutes) to run this algorithm: "))
seconds = minutes*60
start = time()
Trips.get_all(seconds)
end = time()
diff = end - start
m, s = divmod(diff, 60)
h, m = divmod(m, 60)
print "Time taken for algorithm is %d:%02d:%02d" % (h, m, s)
|
"""
multi processのテスト
https://corgi-lab.com/programming/python/python3-multi-thread/
threadインスタンスを生成
"""
import time
import threading
def proc():
for i in range(0,5):
time.sleep(1)
print("count", i)
if __name__ == '__main__':
th1 = threading.Thread(target=proc)
th2 = threading.Thread(t... |
"""
__call__は関数っぽく呼び出したら発動
"""
class A:
def __init__(self, a):
self.a = a
print("A init")
def __call__(self, b):
print("A call")
print(b + self.a)
def main():
a = A(1)
a(2)
a(3)
if __name__ == "__main__":
main()
|
from math import *
import numpy as np
## Class that represents a vehicle.
## Author: Bryan McKenney (based on Java code written by Lucas Guerrette)
class Vehicle:
def __init__(self, dir, vel, pos):
self.dir = dir # Direction vector
self.vel = vel # Velocity vector
self.pos = po... |
"""
Write a program that counts how many of the squares of the
numbers from 1 to 100 end in a 1.
"""
count = 0
for i in range(1, 100):
square = i * i
if square % 10 == 1:
print(square, " = ", i, " * ", i)
count += 1
print("The squares of the numbers from 1 to 100 end in a 1: ", count)
|
"""
Write a program that asks the user to enter a value n , and then computes (1 +
1/2 + 1/3 +...+1/n) − ln(n) . The ln function is log in the math module.
"""
from math import log
n = eval(input("Enter a value:"))
summ = 0
for i in range(1, n):
summ += 1/n
solution = summ - log(n)
print("(1+1/2+1/3+...+1/n) − ln(n... |
"""
Write a program that prints a giant letter A like the one below. Allow the user to specify how
large the letter should be.
*
* *
*****
* *
* *
"""
high = eval(input("How high the box should be:"))
h = int(high/2)
for i in range(h):
p = high-i
print(" "*(p), "*" + " "*(i*2) + "*")
print(... |
"""
Write a program that prints out a list of the integers from 1 to 20 and their squares.
"""
for i in range(20):
print(i+1, '----', (i+1)*(i+1))
|
"""
(a) One way to find out the last digit of a number is to mod the number by 10. Write a
program that asks the user to enter a power. Then find the last digit of 2 raised to that
power.
"""
from math import pow
power = eval(input("Enter a power:"))
resheniye = pow(2, power)
resheniye = resheniye % 10
print(resheniye)... |
"""
Write a program that draws “modular rectangles” like the ones below. The user specifies the
width and height of the rectangle, and the entries start at 0 and increase typewriter fashion
from left to right and top to bottom, but are all done mod 10. Below are examples of a 3 × 5
rectangle and a 4 × 8 .
"""
wide = ev... |
"""
Write a program that asks the user to enter a number and prints out all the divisors of that
number. [Hint: the mod operator is used to tell if a number is divisible by something. See Section
3.2.]
"""
number = eval(input("Enter a number:"))
for i in range(1, number):
if number % i == 0:
print(number, "... |
"""
Ask the user to enter 10 test scores. Write a program to do the following:
(a) Print out the highest and lowest scores.
(b) Print out the average of the scores.
(c) Print out the second largest score.
(d) If any of the scores is greater than 100, then after all the scores have been entered, print
a message warning ... |
"""
Write a program that asks the user to enter a string. The program should then print the
following:
(a) The total number of characters in the string
(b) The string repeated 10 times
(c) The first character of the string (remember that string indices start at 0)
(d) The first three characters of the string
(e) The la... |
import json
import jsonschema
from jsonschema import validate
def get_schema(filename):
"""This function loads the given schema available"""
with open(f'{filename}.json', 'r') as file:
schema = json.load(file)
return schema
def validate_json(json_data):
"""REF: https://json-schema.org/ """
... |
a = 'That dog\'s ass was asking for it'
print('Input a letter an i will tell you if it is in the above')
x = input()
def contains(x):
counter = 0
a = 'That dog\'s ass was asking for it'
for letter in a:
if letter in x:
counter = counter + 1
if counter == 0:
return print(f'{... |
from Sort import *
from Search import *
import time, random
l = [random.randint(0,1000) for i in range(1000)]
sortedL = [random.randint(0,1000) for i in range(1000)]
sortedL.sort()
def elapsedTime(results):
if results:
print(results[2])
print('time elapsed: '+ str(results[1][1] - results[1][0]))
... |
"""
Урок 4. Задание 3.
Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Решите задание в одну строку.
Подсказка: используйте функцию range() и генератор.
"""
a = [i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0]
print(a)
|
numbers = [1,56,234,87,4,76,24,69,90,135]
#to print all even numbers in the list
print(filter(lambda x : x % 2 == 0,numbers))
#to print all odd numbers in the list
print(filter(lambda x : x % 2 == 1,numbers))
|
x = [0, 6, 10]
y = [6.67, 17.33, 42.67]
# p2_x = L0*f(x0) + L1 * f(x1) + L2 * f(x2)
def lx(x, valores_x):
l0 = ((x - valores_x[1]) * (x - valores_x[2])) / ((valores_x[0] - valores_x[1]) * (valores_x[0] - valores_x[2]))
l1 = ((x - valores_x[0]) * (x - valores_x[2])) / ((valores_x[1] - valores_x[0]) * (valores... |
"""Imported the os class
'exe_path' variable stores user input
'files_and_directories' lists 'exe_path'
For loop iterates through the variables"""
import os
def get_executables():
exe_path = input("Enter the path of your executable: ") # path to executable ++.
files_and_directories = os.listdir(exe... |
""" Exploring learning curves for classification of handwritten digits """
import matplotlib.pyplot as plt
import numpy
from sklearn.datasets import *
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
data = load_digits()
print data.DESCR
num_trials = 1000
train... |
months = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7,
'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12,
1: 'January', 2: 'February', 3: 'March', 4: 'April', 5 : 'May', 6 : 'June', 7 : 'July', 8:
'August', 9 : 'September', 1... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
dummy = ListNode(0)
dummy.next = head
while head and head.next:
while head and... |
# 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 dfs(self, root, answer):
if root:
self.dfs(root.left, answer)
answer.append(root.val)... |
class Solution(object):
def containsDuplicate(self, nums):
dic = dict()
for num in nums:
if dic.get(num):
return True
dic[num] = True
return False
|
# Definition for a undirected graph node
# class UndirectedGraphNode(object):
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution(object):
def cloneGraph(self, node):
if not node:
return node
root = UndirectedGraphNode(node.label)
s... |
class Stack(object):
def __init__(self):
self.q1 = []
self.q2 = []
self.size = 0
def push(self, x):
if len(self.q2) == 0:
self.q1.append(x)
else:
self.q2.append(x)
self.size += 1
def pop(self):
if not self.q2... |
class Solution(object):
def generateAbbreviations(self, word):
result = []
def dfs(word, item=''):
if not word:
result.append(item)
for i in range(1, len(word) + 1):
if not item or item[-1].isalpha():
dfs(word[i:], item + st... |
class Solution(object):
def exist(self, board, word):
m, n = len(board), len(board[0])
def dfs(x, y, word):
if len(word) == 0:
return True
# up
if x > 0 and board[x - 1][y] == word[0]:
tmp = board[x][y]
board[x][y] =... |
# 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 closestValue(self, root, target):
delta = abs(root.val - target)
res = root.val
if r... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
list_len = 0
cursor = head
while cursor:
cursor = cursor.next
l... |
# 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 buildTree(self, inorder, postorder):
if len(inorder) == 0 or len(postorder) == 0:
return None
... |
class WordLib():
wordlib_menu = Menu('Word Library Menu', ['Show all words', 'Show by category', 'Add new word', 'Delete word','Exit'])
catergory_menu = Menu('Category', ['Computer Science', 'Fruit', 'Places', 'Names'])
computer_science = ['programming', 'programming language', 'Python', 'Coding Temple',
... |
# -*- coding:utf-8 -*-
'''
类的方法
Created on 2018年10月26日
@author: user
'''
# 类的方法:
# 类的方法也分为公有方法和私有方法,
# 私有方法不能被模块外的类或方法调用,私有方法也不能被外部的类或函数调用。
# 其他语言使用static声明静态方法
# Python使用函数staticmethod()或@staticmethod修饰器把普通的函数转换为静态方法。
# Python的静态方法并没有和类的示例进行静态绑定,要调用只需使用类名作为它的前缀即可
class Fruit(object):
price = 0 # 类变量
... |
# -*- coding:utf-8 -*-
# 函数定义:使用def定义,使用前必须定义,函数的类型即返回值的类型,定义格式如下:
# def 函数名(参数1,参数2...):
# return 表达式
# 参数可以有1个或多个,参数之间用逗号分隔,这种参数成为形式参数
# 函数调用格式如下:
# 函数名(实参1,实参2...)
# 函数的参数:
# python中任何东西都是对象,因此只有引用传参的方式,
# python通过名称绑定的机制,把实际参数的值和形式参数的名称绑定在一起,即:
# 把形式参数传递到函数所在的局部命名空间内,形式参数和实际参数指向内存中同一个存储空间
# 函数参数支持默认值,当某个参数没有... |
# -*- coding:utf-8 -*-
'''
Created on 2018年10月20日
@author: root
'''
#apply():
#python3移除了apply()函数调用可变参数列表的函数的功能只能使用在列表前加*来实现
#filter():
#可以对某个序列做过滤处理,判断自定义函数的参数返回的结果是否为真来过滤,并一次性返回处理结果,声明如下:
#class filter(object)
# filter(function or None,iterable ) --> filter object
def func(x):
if x>0:
return x
... |
input("Press Enter to get started with task#04\n")
radius = int(input("Enter the radius here : "))
print("")
print("Area of circle of the given radius is", (22//7)*(radius**2), "sq. meter")
print("")
input("Hit the Enter key to get out!\nTHANK YOU!")
|
class Solution:
def merge(self, nums1, m, nums2, n):
i,j = m - 1, n - 1
k = m + n - 1
while j >= 0:
if i >= 0 and nums2[j] < nums1[i]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
... |
'''
Question 14
Write a function to find the longest common prefix string amongst an array
of strings. If there is no common prefix, return an empty string "".
'''
'''
Idea
- Do we just iterate throughout each of the strings and access the each one index at a time
- Runtime: N = length of strs, M = min length of a st... |
# name: "TO DO" app (simplified TXT version)
# version: 0.1 (beta)
# author: Valeriy B.
# Usage:
# The app works from keyboard inputs:
# 1. Type a task you want to add to the 'TO DO' app list;
# 2. Type '!print' command to print the tasks from the app list;
# 3. Type '!remove' command to remove a task from... |
s1=str(input("Introduceti primul cuvant exprimat printro variabila: "))
s2=str(input("Introduceti a2 cuvant exprimat printro variabila: " ))
s3=str(input("Introduceti a3 cuvant exprimat printro variabila: "))
s4=str(input("Introduceti a4 cuvant exprimat printro variabila: "))
print("Fraza formata din aceste cuvinte... |
from deck import Deck
from not_enough_chips_exception import NotEnoughChipsError
class Player:
def __init__(self, name: str):
self.name = name
self.hand = list() # Start with an empty list
self.chips = 200
def __enter__(self):
return self
def __exit__(self, type, value, ... |
peso = float (input("Su peso en kilogramos por favor : "))
altura = float(input ("Su altura en metros por favor: "))
IMC = peso / altura**2
print("IMC: " + str(IMC) )
if IMC<20:
print ("Peso Bajo")
elif IMC <= 20 and IMC <= 25:
print ("Normal")
elif IMC <= 25 and IMC <= 30:
print ("Sobrepeso")
e... |
def displayIntro():
print("Welcome. This are a list of non profit you can donate to!")
#put an Introduction message to the users
def displaynonprofit():
print("1. World Central Kitchen")
print("2. Crisis Text Line")
print("3. Heart to Heart International")
#print all the non-profits to the screen... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.5
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Pr... |
def hanoi_tower(n=None):
if n is None:
n = int(input('Please input the tower size: '))
steps = []
x = ['Peg1'] + list(range(1, n + 1))
y = ['Peg2']
z = ['Peg3']
comb1 = [x, '-', y, '-', z]
steps.append("".join(map(str, comb1)))
def tower_solver(n, x, y, z):
if n != 1:
... |
from math import sqrt
def hypotenuse(a,b):
try:
return sqrt(a**2+b**2)
except TypeError:
return None
result = hypotenuse(2,5)
print(result)
result = hypotenuse('2','4')
print(result)
result = hypotenuse(2,'4')
print(result)
|
# coding: utf-8
# @Time : 2018/9/28 9:46
# @Author : Milo
# @Email : 1612562704@qq.com
'''
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
输入: ["flower","flow","flight"]
输出: "fl"
'''
class Solution:
def longestCommonPrefix(self, strs):
#确定共同前缀最小值即循环次数
min_num = min([len (i) for i in strs])
... |
# daj listę zawierające unikalne wartości
lista_a = [10,20,332,23,234,10,435,35,234, 20, 4938, 435, 23]
unikalne = []
for element in lista_a:
if element not in unikalne:
unikalne.append(element)
print(unikalne)
|
if True:
pass
if 5 == 10/2:
print('wnętrze ifa')
if 5 != 20: #zagnieżdzony blok
print('drugi if')
if 5 != 20/4:
print('drugi if')
elif 5 == 5 and 20 % 2 ==1:
print('drugi if,elif')
elif 45 % 3 == 12:
print("elif modulo")
else:
print('instrukcja domyslna') |
# # sprawdź czy jest wygrana w kółko i krzyżyk
# # input: string 9 znaków x,o,n
# #znaki oznaczają pozycje wierszami od górnego
#
#
# # jeśli chodzi o kółko i krzyżyk w zupełności da się to zrobić tylko ze stringami; mamy w sumie dwie możliwości
# # - albo gra jest wygrana albo nierozstrzygnięta, jeśli jest wygrana to... |
#!/usr/bin/python3
users=[]
zhuce=input("Do you want sign up my web? if you want ,please input Y else input N: ")
while zhuce == 'Y':
name=input("Input your name: ")
if name == 'exit':
break
else:
users.append(name)
print(users)
|
import sympy as sym
def main():
x = sym.symbols('x')
s = input("pythonの規則に準拠した数式を入れてください : ")
f = x
exec('f = ' + s)
print(f)
print("積分区間[a,b]を入力してください")
a, b = map(float, input("a,b = ").split())
n = int(input("分割数を入力 : v = "))
h = (b - a) / n
print(a, b, n, h)
ans = f.sym... |
#!/usr/bin/env python3
"""
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once. If you specify a key a second time during the initial creation of a dictionary, then ... |
import sys
# 单引号和双引号是一样的
title = "Meaning"' of '"Life"
print(title)
# 转义序列代表特殊字符(一个特殊字符)
s = 'a\nb\tc'
print(s)
print(len(s)) # 结果为5,他会返回字符串实际长度,无论该字符是如何编码或显示的
# 注意\0与C语言不同
s = 'a\0b\0c'
print(len(s)) # 5
x = 'C:\py\code'
print(x) # 当反斜杠无意义时,直接保留反斜杠C:\py\code
print(len(x)) # 10
# 原始字符串阻止转义
x = r'\n\n\t'
print(x... |
import math
import random
import decimal
from decimal import Decimal
from fractions import Fraction
# 变量与基础表达式
a = 3
b = 4
print(a + 1, a - 1)
# c * 2 # 错误,c没有被定义
# 除法运算
print(b/2 + a) # 在Python3.X中会执行带小数的真除法,结果为5.0
# 在Python2.X中结果为5
print(b//2 + a) # 在Python3.X中执行整数除法,结果为5
# 数值的显示格式
num = 1 / 3.0
print(num)
pri... |
# Load and clean the King County housing prices data set
import pandas as pd
import numpy as np
def load_kc_housing():
king_county_df = pd.read_csv("kc_house_data.csv")
king_county_df = king_county_df[~king_county_df["id"].duplicated()] # Get rid of some duplicate rows
king_county_df["bedrooms"][15870] = ... |
songs = {"1":"Sun",
"2":"Earth",
"3":"Moon",
"4":"Marth",
"5":"Jupiter"}
n = input("Type a number:")
if n in songs:
print(songs[n])
else:
print("sorry...")
|
import sys
def parseArg(data):
parsedStr = string.strip().split(",")
return map(int, parsedStr)
def replaceData(array):
array[1] = 12
array[2] = 2
return array
def getInput(data):
if type(data) == str:
input = parseArg(data)
return replaceData(input)
return data
def com... |
from basic import db,Puppy
# CREATES ALL THE TABLES Model --> Db Table
db.create_all()
# Create two Puppy objects
sam = Puppy('Sammy', 3)
frank = Puppy('Frankie', 4)
# Says none because they do not have ID
print(sam.id)
print(frank.id)
# Puts objects to be added to the database
db.session.add_all([sam, frank])
# Co... |
import pandas as pd
import requests as req
from bs4 import BeautifulSoup as bs
print("Enter the product: ")
search_pro = input()
#url = 'https://www.flipkart.com/search?q=nokia+6.1+plus&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off'
url = 'https://www.flipkart.com/search?q='+str(search... |
'''
This tests our trained data
playing a poker game
'''
from sklearn.externals import joblib
from poker_lib import *
players = [Hand(),Hand()]
table = Hand()
# Each player at the poker table gets
# two cards each
draw_hole_cards(players)
# Draw the flop cards that all players get
draw_flop(players,table)... |
# Fractal triangle
import turtle
from setup import setup
def draw_triangle(step):
for _ in range(3):
turtle.forward(step)
turtle.left(120)
def draw_fractal_triangle(step):
draw_triangle(step)
step /= 2
turtle.forward(step)
turtle.left(60)
return step
de... |
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('satf.csv')
dataset.head(10)
X = dataset.iloc[:,:1]
y = dataset.iloc[:, -1]
X
y
# Splitting the dataset into the ... |
from math import factorial
from itertools import count
def fact():
for i in count(1):
yield factorial(i)
x = 1
for el in fact():
print('Factorial {} - {}'.format(x, el))
if x == 10:
break
x += 1 |
print('Программа деления двух чисел')
first_number = float(input ('Введите первое число и нажмите Enter '))
second_number = float(input ('Введите второе число и нажмите Enter '))
def del_func(a, b):
try:
return print('Результат деления: ', a / b)
except ZeroDivisionError:
print("Деление на ноль ... |
# ***Версия программы с использованием списков ***
month_list = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']
number_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
season_list = ['Зима', 'Весна', 'Лето', 'Осень']
while True... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv, qr
# numpy chapter (ch04)
# ndarray - all elements have to be the same type
data = [6, 7.5, 8, 0, 1]
arr = np.array(data)
data2 = [[1, 2, 3, 4], [8, 9, 19, 11]]
arr2 = np.array(data2)
# array([1, 2, 3, 4], [8, 9, 19, 11)
# property op... |
# this code adapted from https://www.kaggle.com/kplauritzen/elo-ratings-in-python
def get_elo_change(winner_elo, loser_elo, elo_width, k_factor):
"""
https://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details
"""
expected_win = expected_result(winner_elo, loser_elo, elo_width)
change_in... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 20 14:20:05 2018
@author: KKKKKKristian V BLLLLLLLLage
"""
import numpy as np
from random import shuffle
import pygame
from ctypes import windll
def decode(coord):
'''Converts positional coordinates (y, x)
to established cheess-format (a1)'''
return 'abcde... |
# the first derivative
def derivative_one(function, var):
x = [list(var[0]), list(var[0]), list(var[0])] # create an array for inputs to use later
deriv = [] # a list to store the derivatives
for i in range(0, len(var[0])): # a partial derivative is needed for each input
x[0][i] = var[0][i] ... |
import sys
from collections import Counter
def factorial( n) :
res = [None]*500
res[0] = 1
res_size = 1
x = 2
while x <= n :
res_size = multiply(x, res, res_size)
x = x + 1
i = res_size-1
k=""
while i >= 0 :
k+=(str(res[i]))
sys.stdout.flush()
... |
def fibnum(n):
f=[0,1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
print(f[n])
n = int(input())
if n<=1:
print(n)
quit()
fibnum(n) |
# =====================Merge Sort=======================
def MergeSort(arr):
if len(arr)>1:
mid=len(arr)//2
l=arr[:mid]
r=arr[mid:]
MergeSort(l)
MergeSort(r)
i=j=k=0
#copy the data to temp arrays l[] and r[]
while i<len(l) and j<len(r):
... |
for row in range(7):
for col in range(7):
if col==3 or (row==0 and col!=3):
print("*",end="")
else:
print(end=" ")
print() |
'''Simple Interest Calculator'''
P = float(input("Please enter the intial amount: "))
R = float(input("Please enter the rate per year (In decimal format): "))
T = float(input("Please enter the time it is invested (In years): "))
I = P * R * T
print(f"Your simple interest is {I}")
'''
Output:
Please enter the intial... |
'''Sum of First Cubes of N Natural Numbers'''
def sums(n):
sum = 0
for i in range(n):
sum += (i ** 3)
return sum
n = 100
print(f'Sum of cubes of numbers till {n} is {sums(n)}')
'''
Output:
Sum of cubes of numbers till 100 is 24502500
''' |
"""Sum of first n Natural Numbers"""
n = 10
sum = n * (n+1) / 2
print(f"Sum of first {n} Natural numbers is {sum}")
'''
Output:
Sum of first 10 Natural numbers is 55.0
''' |
"""
This Project will seize all youtube video from channel, download each video subtitle, download video, and then edit video
Each function is organized using Pipeline Design Pattern.
##########################Procedure:
1. needs a official API key to get data from youtube
- code source: https://stackoverflow.com/... |
from tkinter import *
convertor= Tk()
def Dollar_in_rupee():
rupee=float(v1_value.get())*71.04
t1.delete('1.0',END)
t1.insert(END,rupee)
v1_value=StringVar()
v1_value=Entry(convertor,textvariable=v1_value)
v1_value.grid(row=0,column=1)
label_1=Label(convertor,text="Input in Dollar")
label_1.grid(row=0,colu... |
'''
hello pyhunters your mation is :
make two functions :
1st function :
Caesar cipher Encode
2nd function :
Caesar cipher decode
مرحبا مجددًا مشروعنا الجديد ينقل بنا الى عالم التشفير
التشفير كان احد اقدم العلوم الانسانية ويطلق عليه التعمية وهو علم تحويل المعلومات من معلومات مقروءة الى معلومات سرية
واستخدم منذ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 16:23:59 2020
@author: Chandini Ganesan
This is a 9X9 Sudoku solver
"""
from random import seed
from random import randint
puzzle=[[0,0,0,0,0,0,2,0,0],
[0,8,0,0,0,7,0,9,0],
[6,0,2,0,0,0,5,0,0],
[0,7,0,0,6,0,0,0,0],
[0,0,0,9... |
#!/usr/bin/python
import re
import urllib
import os
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getImg(html,file):
reg = r'src="(.*?\.jpg)" width'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
i=1
for imgurl in imglist:
urllib.url... |
nil = []
"""QUEUE"""
#creates a queue
def newQueue():
return ("queue", [])
#test if an object is a queue. returns true/false
def isQueue(queue):
return type(queue) is tuple and len(queue) == 2 and \
queue[0] == "queue" and type(queue[1]) is list
#return the contents of the queue
def queueContents(que... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.