text stringlengths 37 1.41M |
|---|
"""
### Exercises
* load the diamonds.csv data set
* identify the distribution for the 'cut' variable with counts by value
* identify the percentage distribution
* add the `dropna=False` argument to make sure there are no null values
"""
diamonds = pd.read_csv('./data/diamonds.csv')
vc1 = diamonds['cut'].va... |
class Tree:
def __init__(self, name='root', classifier = None):
self.children = []
self.name = name
self.classifier = classifier
self.data = {}
def set_data(self, data):
self.data = data
def set_name(self, name):
self.name = name
def set_classifier(sel... |
# Create Neural network classifier
from keras.models import Sequential
iris = datasets.load_iris()
X_iris = iris["data"]
y_iris = (iris["target"])
X_train, y_test, y_train, y_test = train_test_split(X_iris, y_iris, test_size=0.33, random_state=42)
model = Sequential() # initialize
model.add(Dense(12, input_dim=8, a... |
#Gayathri Gude, Michael Yoshimura
#OODA 4448 Homework One, Problem IV
#Bruce Montgomery, Spring 2019
#abstract class
class shapeNames():
def getEdges (self):
pass
def displayFunction(self):
pass
#class for name and edges: Square
class square(shapeNames):
def getEdges(self):
return 4
def dis... |
# the problem is to given the value of n, we need to distribute coins
# of 1 rs, 2 rs, 5 rs in such a way that the number of coins is minimized
# and any value between 1 and n can be formed using those coins
def coins(n):
five_rs_coins = (n - 4) // 5
if (n - 5 * five_rs_coins) % 2==0:
one_rs_coins = 2
... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
receivers, codes = ([] for i in range(... |
from random import randint
def gerador(num):
lista = []
for i in range(0, num):
n = randint(0, 1000)
if n not in lista:
lista.append(n)
return lista
def insertion_sort(lista):
n = len(lista)
for i in range(1, n):
chave = lista[i]
j = i - 1
whil... |
import sqlite3
db = sqlite3.connect("students.db")
c = db.cursor()
#Create list with (mark, id) of each mark from courses
command = "SELECT mark, id FROM courses"
c.execute(command)
gradeList = c.fetchall()
#print(gradeList)
#Create list with (name, id) from people
command = "SELECT name, id FROM people"
c.execute... |
"""
Project Euler problem 3
Solution by Charlotte Aten (caten2@u.rochester.edu) 2016
Problem statement:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
"""
class PrimeFactors:
"""
The collection of natural prime factors of a specified integ... |
#!/usr/bin/python
#===================================================================
# This codelet builds a vocabulary by taking unique words from the
# book Moby Dick and intersecting this with lemma names in WordNet.
# For each remaining word, the synsets for it are looked up and
# all lemmas extracted. Lemmas co... |
def reverse_using_for(s):
s1 = ''
for i in s:
s1 = i + s1
return s1
def reverse_using_recursion(s):
if(len(s) == 0):
return s
else:
return reverse_using_recursion(s[1:]) + s[0]
def reverse_using_built_in(s):
return s[::-1]
s = input('Enter a string to reverse:')
print(... |
def win(p, q):
if (p[0] <= q[0] and p[1] > q[1]) or (p[0] < q[0] and p[1] >= q[1]):
return p
elif (p[0] >= q[0] and p[1] < q[1]) or (p[0] > q[0] and p[1] <= q[1]):
return q
else:
return False
def mergesort(arr, s):
if len(arr) > 1:
mid = len(arr)//2
... |
"""
Dictionary / HashMap
list
f : index --> value
(int) (anything)
(unique) (not unique)
f : anything --> anything
key --> value
(unique) --> (not unique)
{}
"""
words = {
'i': 76,
'am': 100,
'batman': 9
}
numbers = set()
print(type(numbers))
# print(type(words))
print(words)... |
def sumNNaturalNumbers(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
def permutation(n, r): #nPr = n! / (n - r)!
return factorial(n) // factorial(n - r)
def combination(n, r): #nCr = ... |
n = int(input())
# 1 . 2 * 3 * ... * n
# 0! = 1
factorial = 1
i = 1
while i <= n:
factorial *= i
i += 1
print(factorial)
|
a = int(input())
b = int(input())
# addition (+)
print(a + b)
# subtraction (-)
print(a - b)
# multiplication (*)
print(a * b)
# division (/) --> floating
print(a / b)
# power operator (a ^ b) ^ --> **
print(a ** b)
# integer division (//) --> int
# a // b = int(a / b)
# Modulus Operator (%) --> remainder
print(... |
number = int(input())
# number! = 1 * 2 * 3 * .. * number
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print(factorial)
|
"""
Empployee Management System for multiple Employees
Author : Jayaprakash
Created Date: 16-Aug-2021
Modified Date: 16_AUG_2021
"""
import sys
import re
class Employees:
def __init__(self,Employee_count):
self.Employee_count=Employee_count
self.Employee_name=None
self.ACE_numbe... |
#!/usr/bin/env python
from os import path
import numpy as np
# -- pseudo-potential file reading utility
def read_pseudo(filename):
"""
Input
=====
filename
string giving the path to the pseudo-potential file
Returns
=======
G_vectors
2D array of shape (N, 3) where N is the... |
# One Away
def one_away(string_1, string_2):
# One Character Removed from String 2
if (len(string_1) - len(string_2)) == 1:
for pos in range(len(string_1)):
if string_1[pos] != string_2[pos]:
if string_1[pos + 1:] == string_2[pos:]:
return True
... |
"""function used to calculate tanh of a given tensor."""
from sympc.approximations.sigmoid import sigmoid
def _tanh_sigmoid(tensor):
"""Compute the tanh using the sigmoid approximation.
Args:
tensor (tensor): values where tanh should be approximated
Returns:
tensor (tensor): tanh calcul... |
#Registration From in Python
from tkinter import *
import sqlite3
root = Tk()
root.geometry("500x500")
root.title("Registration From")
# Full name = StringVar()
# Email = StringVar()
# Var = Int Var()
# c = StringVar()
# Varl = IntVar()
def database():
name1 =entry2.get()
email=entry3.get()
... |
class Property:#属性类
def __init__(self):
self.high = 0
self.width = 0
def setSize(self,size):
self.high,self.width = size
def getSize(self):
return self.high,self.width
p=Property()
p.high = 10
p.width = 5
print(p.getSize())
p.setSize((150,100))#setSize(self,size);(150,100) ... |
class MartialArts():
def __init__(self, name, type_of):
self.name = name
self.type_of = type_of
self.score = 0
self.blurb = ''
# whenever we use self, we are referring to something that is
# inherent in the class instance, when self is missing, we are using parameters
def add_score(self, user_s... |
from collections import Counter
n = input()
ll = map(int, input().split())
most = Counter(ll).most_common()
max = most[0][1]
ans = []
for m in most:
if m[1] == max:
ans.append(m[0])
print(" ".join(str(s) for s in sorted(ans)))
|
def e248_Greedy(nums):
'''
貪心法
針對整個 list 尋找最大和
可以不取某些數字
'''
sum = 0
max = 0
for n in nums:
sum += n
if sum <0:
sum = 0
if sum > max:
max = sum
return max
def e248_BF(nums):
'''
暴力法 O(n**3)
'''
max = 0
for L in ra... |
# Largest Empty Interval #最長連續空格 #最長連續1
a = [0, 1, 1, 1, 0, 1, 1, 0, 1, 1]
# array[i]:障礙物為0,空白為1。
def longestRC(n):
'''
遞迴解法
'''
if n<0:
return 0
elif n==0:
if a[n] == 0:
return 0
else:
return 1
else:
if a[n] == 0:
return 0
... |
'''
#數學函數 #無條件捨去
'''
import math
N = int(input())
for i in range(N):
x = int(input())
ans = math.sqrt(x)
if ans == int(ans):
print('Yes')
else:
print('No')
|
server_os = {'windows':1,'unix':2,'linux':3}
def my_function(server_os):
for i,j in server_os.items():
if i == 'windows':
print(j)
elif i == 'unix':
print("Yes!we found unix")
else:
print("Yes!we found all the vmware os !!")
... |
import array as arr
vals = arr.array('i', [23,12,56,78,90])
print("Original array is: ")
for i in vals:
print(i)
print ()
print("Reverse Array is: ")
vals.reverse()
e=0
while e<len(vals):
print (vals[e])
e+=1 |
def fibo(n):
a=0
b=1
if n<0:
print("Invalid Input")
elif n==1:
print (a)
else:
print (a)
print (b)
for i in range (2,n):
c = a + b
a = b
b = c
if c>100:
break
else:
... |
# This program removes a recurring newline phrase from corpus of text.
myText = '''I think we should meet at 8pm. You can shop before and
pick up the shoes you need, without anyone having to hang around
while you try them on.
Save Copy Delete
Why don't we meet earlier so we can grab a beer before eating?
Save Copy ... |
import sys
#merge sort in a stable form taking into account order time
def mergesort(arr):
if len(arr)>1:
midpoint = len(arr)//2
left_half = arr[:midpoint]
right_half = arr[midpoint:]
mergesort(left_half)
mergesort(right_half)
i = 0
... |
'''
Problem
Using only primitive types, implement a fixed-size hash map that associates string keys with arbitrary data object references (you don't need to copy the object). Your data structure should be optimized for algorithmic runtime and memory usage. You should not import any external libraries, and may not use p... |
#Knuth-Morris-Pratt's pattern matching Algo
#Final Complexity: O(m+n)
#Subroutine to calculate the prefix/suffix mapping of the pattern
#Time complexity: O(n)
#Space complexity: O(n)
def sconst(pattern):
p_relation = [0 for i in range(len(pattern))]
i = 0
j = 1
while j < len(pattern):
if patte... |
class LinkedList:
def __init__(self, ll=None):
self.root = ll
self.tail = ll
def insert(self, data):
if not self.root:
self.root = LinkedList.Node(data)
self.tail = self.root
else:
self._insert(data)
def _insert(self, data):
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 19:31:59 2018
@author: Midori
@various solutions for Fibonacci
"""
def get_fibonacci_array(base):
fib_list = []
for i in range(base):
if i == 0 or i == 1:
fib_list.append(1)
else:
fib_list.append(fib_l... |
# input()으로 입력받은 자료가 애초에 숫자로 사용할 목적이라면
# 받은 자료를 다시 숫자로 변환해줘야 합니다
# 숫자를 변환할때는 int("변환대상") 을 이용합니다
# int("변환대상")은 변환대상이 숫자 베이스로 된 문자라면
# 그것을 정수로 변환해줍니다 ex) "29 -> 29
price = input("가격을 입력해주세요")
num = input("개수를 입력해주세요")
sum = int(price) * int(num)
print("총액은",sum,"원 입니다") |
def plus(x):
x = x + 1
return x
def str_if_None(*args):
# y = 10
# x = plus(x)
# print(x)
# return (y, x if x else "")
for arg in args:
if arg:
return arg
else:
return ""
res, res2 = str_if_None('a')
print(res)
print(res2)
# def myfunc(a, b):
# r... |
pre = ["pentillion", "quadrilion", "trillion", "billion", "million", "thousand", ""]
final = []
def NoToWord(no):
word = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
tenth = ["", " ", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"]
EleN... |
import os
import csv
voterlist = []
candidatelist = []
candidatefull = []
csvpath = os.path.join("Resources","election_data.csv")
with open(csvpath, "r") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# skip the first line as it contains the headers
next(csvreader, None)
for row in ... |
from turtle import *
speed(-1)
shape("turtle")
color("black")
for i in range(50):
circle(100)
left(7.2)
mainloop()
|
numb = [5, 7, 300, 90, 24, 50, 75]
print("Hello, my name is Hiep and here is my flock", numb)
print("Now my biggest sheep has size", max(numb) ,"let's shear it")
index = numb.index(max(numb))
numb[index] = 8
print("After shering, hear is my flock ", numb, sep = ", ")
for i in range(3):
print("Month {0}".format(i... |
"""
FUNCTIONS NEEDED FOR FORWARD PROPAGATION
"""
import numpy as np
from elementary_functions import *
def linear_forward(A_prev , W , b):
"""
Implements linear part of the NN forward propogation
Input:
A_prev : Activations matrix of the previous layer which serves as input to the present layer. Dimensions : (... |
word1 = "good"
word2 = "day" # define 3 variables
word3 = "john"
sentence = word1 +" " + word2 + " " + word3 # concatenate and store in sentence var
print(sentence) # print sentence var
|
#!/usr/bin/env python
# coding=utf-8
# thx for http://qinxuye.me/article/mid-and-url-in-sina-weibo/
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62_encode(num, alphabet=ALPHABET):
"""Encode a number in Base X
`num`: The number to encode
`alphabet`: The alphabet to ... |
from datetime import datetime
class Account():
def __init__(self,name,phone,loan_limit):
self.name=name
self.phone=phone
self.balance=0
self.loan_limit=loan_limit
self.transactions=[]
self.withdrawal=[]
self.save_lo... |
name1 = input("Whats your first name ")
name2 = input("Whats your second name ")
name3 = input("Whats your third name ")
print(name1,name2,name3)
|
word = input("Enter word: ")
n = input("Enter n: ")
n = int(n)
start = 1
counter = 0
wordsArray = []
while start <= n:
words = input()
if words == word:
counter += 1
wordsArray = wordsArray + [words]
start += 1
print(str(word) + " is found: " + str(counter) + " times.")
|
def count_zero_neighbours(numbers):
start = 0
end = len(numbers) - 1
result = []
count = 0
for number in numbers:
if start < end:
neighbour = numbers[start + 1]
if number + neighbour == 0:
count += 1
result += [number]
... |
n = input("Enter n: ")
n = int(n)
start = 1
numbers = []
while start <= n:
number = input()
number = int(number)
numbers += [number]
start += 1
minimum = numbers[0]
for number in numbers:
if number < minimum:
minimum = number
print("Min is : " + str(minimum))
|
start = 1
while start <= 10:
print(start)
start += 1
end = 10
while end >= 1:
print(end)
end -= 1
|
n = input("Enter n : ")
n = int(n)
start = 1
numbers = []
while start <= n:
number = input()
number = int(number)
numbers += [number]
start += 1
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
|
from random import randint
n = input("Enter sides :")
n = int(n)
result = randint(1,n)
print(result)
|
n = input("Enter n: ")
n = int(n)
mult = 1
while n != 1:
if n == 0:
break
else:
mult = mult * n
n = n - 1
print(mult)
|
n = input("Enter n: ")
n = int(n)
k = 20
if n > 20 and n % 2 ==0:
print("Yes it is")
else:
print("No it is not!!")
|
a = input("Enter a: ")
a = int(a)
b = input("Enter b: ")
b = int(b)
operation = input("Enter operation: ")
if operation == "+":
print(a + b)
elif operation == "-":
print(a - b)
elif operation == "*":
print(a * b)
elif operation == "/":
print(a / b)
else:
print("There is no such operation")
|
import unittest
from BasicMath import BasicMath
class LearnTestClass(unittest.TestCase):
def setUp(self) -> None:
print("Setup is called")
self.bm = BasicMath()
def tearDown(self) -> None:
super().tearDown()
print("Tear Down Called......")
def test_Add(self):
res... |
#LAMBDA Simplificar la funciones
"""def area_triangulo(base,altura):
return (base*altura)/2
triangulo1=area_triangulo(5,7)
triangulo2=area_triangulo(9,6)
print(triangulo1)
print(triangulo2)"""
#Simplificar la sintaxis
area_triangulo=lambda base,altura:(base*altura)/2
print(area_triangulo(7,5))
print(area_triangul... |
import pandas as pd
import matplotlib.pyplot as plt
score_list = pd.Series([49, 44, 46, 42, 48, 45, 44, 45, 42, 43, 47, 41])
putt_list = pd.Series([17, 17, 16, 18, 19, 17, 16, 16, 16, 15, 18, 17])
chip_list = pd.Series([17, 7, 11, 8, 11, 8, 14, 10, 13, 14, 14, 6])
fir_list = pd.Series([3, 2, 3, 2, 2, 2, 2, 2, 3,... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 13 2016
@author: Matthew Carse
"""
#@ Class with functions to mutate and recombine sequences.
#@ Mutation randomly replaces one of the anchor-chain combinations
#@ in a chromosome with one from the list of 400 possibilities.
#@ Recombination involves cleaving t... |
#This program uses dynamic programming to find whether a single string can be broken up
#into english words
#Author: Mac Weinstock
#USAGE: python3 dynProg.py < [FILENAME]
import sys
#Read in 10k word dictionary
def readDict(file):
tempDict = []
f = open(file, "r")
for line in f:
tempDict.append(line)
f... |
from collections import defaultdict
from collections import deque
from heapq import *
class Exchange_Node:
def __init__(self, price, time_stamp):
self.price = price
self.time_stamp = time_stamp
def __str__(self):
result = "Price {} with timestamp {}".format(self.price, self.time_stamp... |
from Board import Board
from copy import deepcopy
from Player import FloodItPlayerSimulator
class Game:
"""
An abstract class used to represent the Game.
Need to implement play_game() method.
"""
@classmethod
def play_game(self,):
raise NotImplementedError
class FloodItGame(Game):
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#使用lambda来创建匿名函数。
'''
1、lambda 主要用来创建匿名函数,def 用来创建带名称的函数
2、lambda 是一个表达式(可以快速创建单行最小函数),而 def 是一个函数语句
3、lambda 可以直接把函数赋值给一个变量,用变量名来表示函数名,并且调用
4、lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值,lambda 函数不能包含命令,包含的表达式不能超过一个
5、lambda的一般形式是关键字lambda后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式(相当于函数体)。la... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#计算字符串长度。
'''
str为字符串
str.isalnum() 所有字符都是数字或者字母
str.isalpha() 所有字符都是字母
str.isdigit() 所有字符都是数字
str.islower() 所有字符都是小写
str.isupper() 所有字符都是大写
str.istitle() 所有单词都是首字母大写,像标题
str.isspace() 所有字符都是空白字符、\t、\n、\r
'''
while True:
str = input('请输入字符及数字:')
if str.isalnum():
print... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#列表排序及连接。 排序可使用 sort() 方法,连接可以使用 + 号或 extend() 方法。
list1 = [1,55,6,3,99]
list2 = [100,5,88,40,9]
list1.sort()
print(list1)
# list1.extend(list2)
# print(list1)
print(list1+list2)
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
# >>> conn = sqlite3.connect('test.db') #连接数据库
# >>> cursor = conn.cursor() #创建游标
# # 执行查询语句:
# >>> cursor.execute('select * from user where id=?', ('1',)) #执行sql语句 但是不返回具体结果,仅仅是执行动作
# <sqlite3.Cursor object at 0x10f8aa340>
# # 获得查询结果集:
# >>> values = cursor.fetchal... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。
# 问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。
# 请问第五个人多大?
def age(n):
if n ==1:
return 10
elif n ==2 :
return 10+2
else:
return age(n-1)+2
n = int(input('请输入人员个数:'))
print(age(n))
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#题目:从键盘输入一些字符,逐个把它们写到磁盘文件上,直到输入一个 # 为止。
fp = open('test.txt','a+') #a+ 表示可追加并读写
while True:
s = input('请输入字符:')
if s != '#':
fp.write(s)
else:
break
fp.seek(0)
print(fp.read())
all_the_text = open('test.txt').read()
print (all_the_text)
fp.close()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,
低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,
高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,
高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,
求应发放奖金总数?
'''
x = int(input('请输入当月利润:'))
if x <= 10:
q... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#题目:循环输出列表
list = ['sa','li','na','mm']
for i in range(4):
print(list[i])
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# print('sss','dd','dfadf') #一次性输入多个字符串
#
# print('100+200 = %d' %(100+200))
# print('100+200 = ',(100+200))
#
# a = 'ABC' #解释器创建了 字符串"ABC"和变量'a',并把a指向了'ABC'
# b = a #解释器创建了 变量b,并把b也指向了'ABC'
# a = 'XYZ' #解释器创建了 字符串"XYZ",并把a指向了'XYZ'
# print(b)
#
# print(10/3)
# print... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
1、为了类属性的安全,一般会限制外部直接读取类属性及赋值,所以可以将属性设置为私有变量,然后在类里面定义一个获取属性get_attr()
和设置属性 set_attr() 的方法、同时可以方便检查参数,然后提供外部调用,只不过步骤繁琐了些
2、为了简化操作,可以使用python 内置的 @property 装饰器 负责把一个方法变成属性调用
3、
'''
class Student(object):
@property #可以把getter()方法变成属性
def score(self):
return self._s... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import unittest
from student import Student
class TestStudent(unittest.TestCase):
def setUp(self):
print('setUp...')
def tearDown(self):
print('tearDown...')
def test_init(self):
s = Student('chenyan',90)
self.assertEqual(s.n... |
"""
pretty_helper.py
Contains all of the functions that do the actual analyzing and formatting of the lines of a text file.
"""
import re
def to_text(lines):
"""Re-joins the lines into a single newline-separated string."""
return '\n'.join(lines)
def search_backwards(lines, i):
"""Search backwards unt... |
import datetime
def daterange(date1, date2):
"""
:param date1: start date
:param date2: end date
:return: a list of date
"""
for n in range(int((date2 - date1).days) + 1):
yield date1 + datetime.timedelta(n)
def date_format(date):
list_date = date.split("-")
year, month, day... |
#this program calculate vol of cylinder given Radius and Heigfht
#cylinder volime = pi * (raduius**2)*height
import math
import argparse
import sys; sys.argv=['']; del sys
parser = argparse.ArgumentParser(description='Calculate volume of a Cylinder')
parser.add_argument('-r','--radius',type=int,metavar='',required=Tru... |
#模拟atom进行数据预处理
import pandas as pd
pd.set_option('display.max_rows',None)
#train_data = pd.read_csv("G:/taodata/project/xiaohua_finance/data_0116_sinjor_rand_v1/input/sinjor_train_data_rand.csv",dtype = "str")
#train_data = pd.read_csv("G:/taodata/project/xiaohua_finance/data_0116_sinjor_rand_v3_used_all/input/sinjor_... |
"""
Random Walk using Monte Carlo Simulation, or probability simulation, which is a
technique used to understand the impact of risk and uncertainty in financial,
project management, cost, and other forecasting models.
When you have a range of values as a result, you are beginning to understand
the risk and uncertainty... |
#!/usr/bin/env LearnPythonNotes
# An alarm has a 4 digit code on a keypad [0-9] with 10 digits
# How many posible purmutations can we have, when order matters.
# Import libraries
##import math
from math import factorial
from math import sqrt as square_root
# Variables of sclar types and values:
# int 42, -3
# float 4... |
# Import a packages to extend Python (just like we extend Sublime, Atom, or VSCode)
from random import randint
# re-import our game variables
from gameComponents import gameVars, winLose, rpsCompare
# player_choice == False
while gameVars.player_choice is False:
print(" ")
print("-------/* Rock, Paper, Scissors G... |
'''
Вашей программе на вход подаются две строки s и t, состоящие из строчных латинских букв.
Выведите одно число – количество вхождений строки t в строку s.
Пример:
s = "abababa"
t = "aba"
Вхождения строки t в строку s:
abababa
abababa
abababa
'''
def input_graber(num):
"""
:return: function return tuple of... |
n, k = map(int, input().split())
print(n + k)
x = input().split()
print(x)
map_obj = map(int, x) # f [a, b, c, d] -> f(a), f(b), f(c), f(d)
print(map_obj)
n = next(map_obj)
print(n)
k = next(map_obj)
print(k)
print(n + k)
# Рассмотрим класс filter который возвращает итератор значений в которых функция вовращает tr... |
from typing import List
from malcolm.compat import OrderedDict
class StateSet:
def __init__(self) -> None:
self._allowed = OrderedDict()
# These are all the states we can possibly be in
self.possible_states: List[str] = []
def transition_allowed(self, initial_state: str, target_state... |
class Quiestion():
def __init__(self, ques_name, answer_list, right_answer):
self.question = ques_name
self.answers = answer_list
self.right_answer = right_answer
if right_answer not in answer_list:
print('Right answer not in answers list!')
class Quiz():
def __ini... |
#! python3
# indenter.py - making effective use of python context manager
class Indenter:
def __init__(self):
self.level = 0
def __enter__(self):
self.level+=1
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.level-=1
def print(self,text):
... |
# -*- coding: utf-8 -*-
# lesson 3.7: XML, library ElementTree, library lxml.
from xml.etree import ElementTree
from random import random
'''
tree = ElementTree.parse("example_copy.xml")
root = tree.getroot()
# use root = ElementTree.fromstring(string_xml_data) to parse from str
#print(root)
#print(root.tag, root.attr... |
# -*- coding: utf-8 -*-
# lesson 1.5: Introduction to Classes
# MoneyBox
'''
class MoneyBox:
def __init__(self, capacity):
"""Конструктр с аргументов - вместимости копилки"""
self.capacity = capacity
self.quantity = 0
def can_add(self, v):
"""True, если можно добавить v монет, иначе False"""
if v <= (se... |
# Guessing Game
import time
import random
import sys
import os
TheGoodNumber = str(random.randint(1,10))
python = sys.executable
def DrawBoard(x):
x = str(x)
if x == TheGoodNumber:
print("="*30)
print("=" + " " * 28 + "=")
print("=" + " " * 28 + "=")
print("= ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.util import strtobool
def ask(question, default=True):
prompt = question
if default == None:
prompt += ' [y/n] '
elif default:
prompt += ' [Y/n] '
else:
prompt += ' [y/N] '
while True:
try:
ans... |
from Graph import Graph
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
class Search:
def __init__(self):
self._path = []
self._path_cost = 0
def _calculate_latest_path_cost(self):
if l... |
import sqlite3
import traceback
import sys
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
sqlite_insert_query = """INSERT INTO unknown_table_1
(id, text) VALUES (1, 'Demo Tex... |
# Leia uma matriz 5 x 3 com as notas de 6 alunos em 3 provas.
# Em seguida, escreva o numero de alunos cuja pior nota foi na prova 1,
# a quantidade de alunos cuja pior nota foi na prova 2, e a quantidade
# de alunos cuja pior nota foi na prova 3.
# ------------------------------------------------\\--------------------... |
# Faça um programa que permita ao usuário criar uma matriz de 3 x 3 números inteiros.
# Em seguida, gere um array unidimensional pela soma dos números de cada coluna da matriz e mostrar na tela esse array.
# #Por exemplo, a matriz:
# 5 -8 10
# 1 2 15
# 25 10 7
# Vai gerar um vetor, onde cada posição ... |
# As Organizações Tabajara resolveram dar um aumento de salário
# aos seus colaboradores e lhe contraram para desenvolver o programa
# que calculará os reajustes.
#
# Faça um programa que recebe o salário de um colaborador e o
# reajuste segundo o seguinte critério, baseado no salário atual:
#
# salários até R$ 280,00 ... |
# Lista de listas
mercado = [['pera', 100, 4.9], ['manga', 20, 3.9], ['uva', 30, 5.9], ['caju', 15, 3.5]]
print(mercado)
mercado[1][2] *= 0.5 # manga pela metade do preço
print(mercado)
mercado[3][1] -= 10
print(mercado) # caju com dez quilos a menos
mercado.remove(['uva', 30, 5.9]) # o produto uva é removido do me... |
# Exemplos de Navegação em Arquivo Binário
#Subprogramas
# Verificando o avanço do cursor de leitura/escrita
def verificaAvancoCursor():
import struct
try:
with open('arquivo.bin', 'rb') as arq:
pos = arq.tell()
print('O cursor está no endereço', pos)
x = struct.unp... |
"""
John wants to decorate a room with wallpaper.
He's heard that making sure he has the right amount of wallpaper is more complex than it sounds. He wants a fool-proof method for getting it right.
John knows that the rectangular room has a length of l meters, a width of w meters, a height of h meters.
The standard... |
from logica import filme
def menu_adicionar():
print ("\nAdicionar Filme \n")
titulo =input("Titulo: ")
genero = input("Genero: ")
ano = input("Ano: ")
filme.adicionar_filme(titulo, genero, ano)
def imprimir_filme(_filme):
print ("Titulo: ",_filme[0])
print ("Genero: ",_filme[1])
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.