text stringlengths 37 1.41M |
|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
class ConvNet(object):
"""
This class implements a convolutional neural network in TensorFlow.
It incorporates a certain graph model to be trained and to ... |
a = True
b = False
print("a is ", a)
print("b is ", b)
print("Boolean of 0 is ", bool(0))
print("Boolean of 1 is ", bool(1))
print("Boolean of 2 is ", bool(2))
print("Boolean of -1 is ", bool(-1))
print("Boolean of a == b is ", a == b)
c = ""
print("Boolean of an empty string in ", bool(c))
c = " "
prin... |
import re
def main():
str = "Marvellous Infosystems , hello good morning"
x = re.findall("llo",str)
print(x)
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")
if __name__ == "__main__":
... |
#函数外定义的叫做全局变量
name = "ziyichen"
def fun():
global name
print("inner input the global variable: ",name)
name = "qianyu"
fun()
print("outer input the global variable: ",name) |
""" Moduł dostarczający funkcji generujących zbiory / wartości losowe """
import numpy as np
from typing import Tuple
from numpy import random
def dist(point_a, point_b):
return np.sqrt((point_a[0] - point_b[0])** 2 + (point_a[1] - point_b[1])**2)
def rand_seg_point(point_a, point_b):
""" Zwraca losowy punkt... |
import random # import random module
guessesTaken = 0 # make the value of guessesTaken variable equal zero
print('Hello! What is your name?') # print to console
myName = input() # make the value of myName variable equal user input
number = random.randint(1, 20) # make the number variable return a random integer... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 30 11:44:47 2017
@author: saurabhmehra
"""
def genPrimes():
primes = []
n = 2
primes.append(n)
yield n
while True:
n+=1
for num in primes:
if n % num == 0:
break
else:
... |
import sys
class Board:
# TicTacToe Board
board = {"TL": ' ', "TM": ' ', "TR": ' ',
"ML": ' ', "MM": ' ', "MR": ' ',
"LL": ' ', "LM": ' ', "LR": ' '}
def __str__(self):
# Print Board contents
return self.board['TL'] + '|' + self.board['TM'] + '|' + self.board['TR'] + '\n' + \
'-+-+-' + ... |
import printf
def fib(n):
if n == 0 or n == 1:
return 1
else:
# print "f(" + str(n-1) + ") + f(" + str(n-2) + ")"
return fib(n-1) + fib(n-2)
x = int(raw_input("Enter a number: --->"))
if x < 0:
print "Input Correct No."
else:
for i in range(0,x):
printf.printf(str(fib(i)) + ",")
|
def cumsum(l):
for i in range(len(l)):
for j in range(i):
l[i]=str(int(l[i])+int(l[j]))
l1 = ['1','2','3','4','5']
print len(l1)
cumsum(l1)
print l1
|
"""
task:- Your task is to wrap the string into a paragraph of width w.
Input Format:-
The first line contains a string, S.
The second line contains the width, w.
Output Format:- Print the text wrapped paragraph.
"""
"""
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
"""
import textwrap
def wrap(string, max_width):
... |
"""
Input Format:- A single line containing the space separated values of M and N.
Output Format:- Output the design pattern.
"""
"""
7 21
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
n,m=input().split()
c='|'
v='.'
n=int(n)
m=int(m)
j=n//2-1
for i in range(n):
if i... |
'''Description: PEuler 30 - Digit fifth powers
Q: Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
See: https://projecteuler.net/problem=30
Date: August 26, 2019
'''
def main():
num_list = []
max_sum = 6 * 9**5
for x in range(2, max_sum):
... |
'''Description: PEuler 23 - Non-abundant sums
Q: Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
See: https://projecteuler.net/problem=23
Date: August 25, 2019
'''
import math
import time
def main():
start_time = time.time()
# Generate list o... |
'''Description: PEuler 25 - 1000-digit Fibonacci Number
Q: What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
See: https://projecteuler.net/problem=25
Date: August 25, 2019
'''
def main():
fibonacci_list = [0, 1]
index = 0
while True:
next = sum(fibon... |
'''Description: PEuler 31 - Coin sums
Q: How many different ways can £2 be made using any number of coins?
See: https://projecteuler.net/problem=31
See: https://www.mathblog.dk/project-euler-31-combinations-english-currency-denominations/ for Dynamic Programming explanation.
Date: August 26, 2019
'''
d... |
#!/usr/bin/python
import random
"""
Programming problem #1
CREDIT: https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/
Game loop (while)
1. Randomly choose number between 1 and 6
2. Print chosen number
3. Ask if you'd like to roll again
4. Need to set ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Python 练习栗子
'''
# 打印随机数
import random
print random.random() # 输出0-1之间的随机数
print random.uniform(10,50)
print random.randint(1,100) #随机整数
# 位运算
# if __name__ == '__main__':
# a = 077
# b = a & 3
# print 'a & b = %d' % b
# b &= 7
# print 'a & b = %d' ... |
#Ave César
def cifrar(mensaje,clave):
resultado = ""
for letra in mensaje:
if letra == " ":
resultado = resultado + " "
else:
resultado = resultado + abecedario[(abecedario.find(letra)+clave)%len(abecedario)]
return resultado
def descifrar(mensaje,clave):
... |
import display
# OCR言語の入力処理を行う関数
def inputLang():
langList = (1, 2) # 存在する言語のリスト(型はタプル)
langDict = {"1":"日本語", "2":"英語"}
display.showCaption_Em("OCRの言語を選んでください")
print("1・・・日本語")
print("2・・・英語")
print("*----------------------------------------*")
lang = input()
# 整数が入力されているかのチェック
... |
Num1 = input("Enter first number: ")
Num2 = input("Enter second number: ")
Sum = int(Num1) + int(Num2)
Sub = int(Num1) - int(Num2)
Mul = int(Num1) * int(Num2)
if int(Num2) != 0:
Div = int(Num1) / int(Num2)
else:
Div = "Can't divide by zero"
print(Sum)
print(Sub)
print(Mul)
print(Div)
file = open("multiops_r... |
s1=str(input('enter the string'))
s2=[::-1]
if s1=s2:
print('string is pallindrome')
else
print('string is not pallindrome')
|
import sqlite3
banco = sqlite3.connect('filmes.db')
sql = banco.cursor()
sair = 'n'
def TodosFilmes():
sql.execute("SELECT * FROM filmes")
print('Esses são todos os filmes cadastrados:')
for row in sql.fetchall():
print('ID:', row[0])
print('Nome:',row[1])
print('Duraçã... |
student_count = int(input("How many students do you have? "))
students={}
def student():
for i in range (student_count):
fname = input("Students name: ")
student_grade = input ("Student Grade: ")
student_course = (input("Student Course: "))
student()
print(students) |
############ Step 1
# This is where we shape the data into a workable form
### Import Data
data_raw = pd.read_csv('../input/train.csv')
data_val = pd.read_csv('../input/test.csv')
data1 = data_raw.copy(deep = True)
data_cleaner = [data1, data_val]
### Initial Analysis of data
print (data_raw.info())
print(data_raw.s... |
class Reader:
def __init__(self, filename):
self.filename = filename
self.vectors = []
def read(self):
f = open( self.filename )
self.vectors = f.readlines()
self.vectors = [line.rstrip() for line in self.vectors]
def getVectors(self):
retur... |
MAX_KEY_SIZE = 26
def getTranslatedMessage(message, key):
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
... |
cig = float(input('Quantos cigarros voce fuma por dias ? '))
mintp = cig*10
hrtp = mintp//60
diatp = hrtp//24
hrp = hrtp%24
minp = mintp%60
print('Voce perdeu {} dias {} horas e {} min de vida \n Pare de fumar , faz mal'.format(diatp,hrp,minp))
|
#-------------------------------------------------------------------------------
# Name: Problem 4
# Purpose:
# A palindromic number reads the same both ways. The largest
# palindrome made from the product of two 2-digit numbers
# is 9009 = 91*99.
# Find the largest palindrom... |
class CoffeeMachine:
def __init__(self, water = 0, milk = 0, beans = 0, cups = 0, money = 0):
self.water = water
self.milk = milk
self.beans = beans
self.cups = cups
self.money = money
def display(self):
print("The coffee machine has:")
print(self.water,... |
f = open('파일명.txt', 'w') # create, open
f.write("데이터 입니다.")
f.close()
f = open('파일명.txt', 'r') # create, open
data = f.read()
f.close()
print(data)
with open('파일명.txt', 'r') as f:
print(f.read())
|
def f(n):
if n == 1 or n == 2:
return 1
fibo = [1,1]
for i in range(n-2):
fibo.append(fibo[-1] + fibo[-2])
return fibo[-1]
print(f(6))
def pass1(): # 구현할 예정인데
pass
|
#!/usr/bin/python3
from math import *
print("Calculate divisors of a number(https://www.practicepython.org/exercise/2014/02/26/04-divisors.html)");
num = input("Input a number: ")
num = int(num)
# notice: range(2, 5) equals list [2, 3, 4] and 5 is not included
i = 0
for i in range(2, int(sqrt(num))):
if num % i ... |
from exemplo_conta import ContaSalario
from operator import attrgetter
# Referência na Doc
# https://docs.python.org/3/tutorial/datastructures.html
idades = [21, 40, 19, 28, 20]
# Métodos referentes a lista
# Exibe o tamanho
len(idades)
# Acrescentando elementos no fim
idades.append(54)
# Percorrendo
# for idade ... |
def fibonacci(i):
if i == 0:
return 0
elif i == 1:
return 1
else:
return fibonacci(i-1)+fibonacci(i-2)
|
def odd(x):
if x % 2 != 0:
return 1 #Odd number
else:
return 0 |
# Taken from https://www.dataquest.io/mission/75
import pandas
import numpy as np
import re
import operator
import matplotlib.pyplot as plt
from sklearn import cross_validation
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomFores... |
import sqlite3
#CRIAR A CLASSE QUE VAI SER RESPONSÁVEL PELO BANCO DE DADOS
class ConectarDB(object):
#MÉTODO CONSTRUTOR QUE FAZ A CONEXÃO COM O BANCO
def __init__(self):
self.conn = sqlite3.connect("todo-app.db")
self.cursor = self.conn.cursor()
self.criar_tabela()
#MÉTODO QUE CR... |
import random
n = input("Enter the number of spears & humans present: ") #asks the user for the amount n for the amount of spears and people
ppl = [ ] #Creates a new empty list of people
spears = [ ] #Creates a new empty list of spears
x = 0 #ensuring the list traverse starts from 0
for x in range(n): #traverses the ... |
import sqlite3
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
"""
conn = None
conn = sqlite3.connect(db_file)
return conn
def total_rows(conn):
"""
Query total number of rows
"""
curs = conn.cursor()
c... |
'''
Use the bult-in class dict in order to make a class that allows us
to read key value pairs from a .txt file and write/modify them in
the .txt file in question (test_exercise_3.txt)
'''
# Proposed solution
class ConfigDict(dict):
def __init__(self, filename):
try:
file_ = open(filen... |
# -*- coding: utf-8 -*-
"""
Prediction of milk production based on real data using RNNs
Estimations are done by RNNs that predict only the following time instant (a single moth)
We aim at predicting a whole year. For a more accurate RNN structure see 'RNN_milk_estimation_future'
Already trained LSTM and GRU networks... |
# -*- coding: utf-8 -*-
"""
Object oriented programming
@author: dcamp
"""
x = 0.2
print(type(x))
print('Note that the variable x is an object (based on pre-built python class)')
print('is x an integer: {}'.format(x.is_integer()))
print('\n')
#############################################################
def hello():
... |
# Polimorphism refers to the idea that different calsses may have the same method name.
# Although the method may do similar things on different classes, generally, they are written differently such that they are applicable to the class in question.
# As classes become more complex, we may whish to initialize an inst... |
import unittest
from summa.keywords import keywords
from summa.preprocessing.textcleaner import deaccent
from .utils import get_text_from_test_data
class TestKeywords(unittest.TestCase):
def test_text_keywords(self):
text = get_text_from_test_data("mihalcea_tarau.txt")
# Calculate keywords
... |
# coding: utf-8
import os
import urllib
import sys
import random
from bs4 import BeautifulSoup
import string
# This program accepts as argument exacalty one (1) web page. It will then proceed to download all images from the page into folder named after the page
# @Author Matti Keskiniemi /Smattiz
# Tää ohjelm... |
#A rock, paper, scissors game
#importing random
from random import randint
our_list = ["Rock", "Paper", "Scissors"]
opponent = our_list[randint(0,2)]
player = False
while player == False:
player = input("Rock, Paper, Scissors?: ")
if player == opponent:
print("It is a tie.")
elif player == "Rock"... |
from os.path import exists
import sys
from pickle import dump, load
import string
import csv
def loadFile(fileName):
"""
Takes raw data from project Gutenberg and cuts out the introduction and bottom part
It also tranfers the entire text to lowercase and removes punctuation
Returns a String
>>> s = 'A***H ... |
#!/usr/bin/python
import numpy
class TrapezoidProfile(object):
"""Computes a trapezoidal motion profile
Attributes:
_acceleration_time: the amount of time the robot will travel at the
specified acceleration (s)
_acceleration: the acceleration the robot will use to get to the target
(unit/... |
# converts list of lists to a flat list without duplicates
def flatten(l):
return list(set([item for sublist in l for item in sublist]))
|
if True:
print(True)
print("Statements")
print("Delimited by whitespace")
num = 12
if num > 5:
print("num is greater than 5")
if num < 30:
print("num is less than 30 and greater than 5")
else:
print("num is less than 5")
if num > 5:
print(num)
elif num < 10: #elif is short fo... |
n1 = int(raw_input("Show numbers from: "))
n2 = int(raw_input("to: "))
y = int(raw_input("divisible by: "))
for x in range(n1, (n2+1)):
if x % y == 0:
print x,
|
# 列表生成式
a = [i + 1 for i in range(10)]
print(a)
# 生成器
a2 = (i for i in range(1000)) # 生成器
print(a2)
# 一个个生成
# print(next(a2))
# print(next(a2))
# print(next(a2))
# print(next(a2))
a3 = (i for i in range(5))
# print(next(a3))
# print(next(a3))
# print(next(a3))
# print(next(a3))
# print(next(a3))
# print(next(a3)) ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head: ListNode) -> ListNode:
# Input: 1->1->2->3->3
# Output: 1->2->3
if head is None:
return None
node = head
while True:
... |
#!/usr/bin/env python
# coding: utf-8
# # Special Pythagorean Triplet
# ### Problem
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
#
# For example, 32 + 42 = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean triplet for which a + b + c =... |
'''
Xinru Yan
July 2020
Inputs:
review: a csv file contains amazon review. Must have the following columns: Text, Published, Brand.
published column must contain a string looks like this: 2014-12-16 00:00:00
aspect: a string represents the aspect to analyze (e.g Smell).
key: a txt file contains... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 11 15:34:25 2017
@author: knollf01
"""
## Simple RGB to grayscale conversion
def rgb2gray(rgb):
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray |
#sum of first n prime numbers using loop
n = int(input("enter a number"))
sum = 0
num = 2
count = 0
while count < n:
i = 2
while i<=num: #check num is prime or not
#for i in range(2, num+1):
if ((num%i) == 0) and (i!=num):
break
if (i == num) or (num==2):
... |
#!/usr/bin/env python
file=open('sun.txt','r') # Open sun.txt file
l=file.readlines() # Read lines and store as list
length=[] # Empty list
for i in l:
length.append(len(i)) # Store length of each line in Empty list
n=max(length) # Figure out maximum length from list
print 'Longest line in file is '+str(n)+'... |
users = {
"Adam": {
"password": "123",
"money": 300,
},
"David": {
"password": "456",
"money": 400,
},
}
while True:
uinput = str(input())
if uinput == "deposit":
amount = float(input("How much? "))
name = str(input("Who's account should the money be deposited to? "))
if name ... |
import statistics
""" data = {
'students': [
{
'name': 'Salvador Vizcaino',
'Class': 2015,
'Scores': [10, 9.8 , 7 , 7.8, 10, 8.9]
},
{
'name': 'Edgar',
'Class': 2015,
'Scores': [10, 7 , 7, 7.8, 10, 9,10]
},
... |
# x=input('1. sayı: ')
# y=input('2. sayı: ')
# toplam=int(x)+int(y)
# print('toplam: ' +str(toplam))
# r=input('yarıcapı giriniz: ')
# r=float(r)
# pi=3.14
# daireninalanı=pi*(r)**2
# darenincevresi=2*pi*(r)
# print('daireninalanı: ',daireninalanı)
# print('dairenin çcevresi: ',darenincevresi)
# name='fatih'
# su... |
# istenen kelimeyi istenen adette yazma.
# def yaz(kelime, kackez):
# x=1
# while (x <= kackez):
# print(kelime)
# x+=1
# yaz('nasilsin', 9)
#yada
# def yazdir(kelime, adet):
# print(kelime*adet)
# yazdir('nasilsin\n', 9)
####################################################
# gönderil... |
##not: iter() metodu sadece iter'i destekleyen class larda çalışır ve liste class'ları destekler.
## iter ile oluşturulan obje next methodu ile çağrılır.
liste=[1,2,3,4,5]
x=iter(liste)
print(next(x)) #listenin sadece bi çevrimde 0. indexini getirir.ve sonraki indexte bekler
#listenin sonraki elemanı için tekrar next... |
# isim=input('isminizi giriniz: ')
# yas=float(input('yaşınızı giriniz: '))
# egitimm_durumu=input('eğitim durumunuz: ')
# hak=yas>=18 and (egitimm_durumu=='lise' or egitimm_durumu=='üniversite')
# if hak:
# print(f'sayın {isim} ehliyet alma hakkınız vardır.')
# else:
# print(f'sayın {isim} ehliyet alma hak... |
"""
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
"""
import math
examples = [
(1, 0),
(12, 3),
(23, 2),
(26, 5),
(1024, 31),
]
def size(x):
round_sqr... |
from turtle import *
from random import randint
speed(0)
head = Turtle()
head.penup()
head.goto(60,200)
head.pendown()
head.color('black')
style = ('Comic Sans', 30, 'bold italic')
head.write('Turtle Race', font=style, align='center')
head.hideturtle()
penup()
file_obj = open("asciiart.txt")
x = file_obj.read()
print... |
## Background Problem Statement
# The US Census Bureau has published California Census Data which has 10 types of metrics such as the population,
# median income, median housing price, and so on for each block group in California.
# The dataset also serves as an input for project scoping and tries to specify the func... |
from lifting import *
x = symbols('x')
polin1 = Poly(x**2-1)
print(polin1)
polin2 = Poly((x-1)**2-1)
print(polin2)
stack = Stack(None, [polin1, polin2])
for c in stack.cells:
print(c.dimension)
print("")
for c in stack.cells:
print(c.sample)
print("\n\n.....\n\n")
polin3 = Poly(x**2+1)
print(polin3)
stac... |
from lifting import *
x, y, z = symbols('x y z')
def printSamples(cad):
print('Samples')
i = 0
for stackList in cad.stackList:
print('stackList: ' + str(i))
j = 0
for stack in stackList:
print('stack: ' + str(j))
cells = stack.cells
print('cells... |
#Python task list example
taskList = []
def commander():
print("\na to add, s to show list, q to quit")
commandOrder = input("Command --> ")
if commandOrder == "a":
addTasks()
if commandOrder == "s":
printTasklist()
if commandOrder == "q":
print("Bye Bye Friend....")
... |
import sys
import re
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
numero_tabelas =len(sys.argv)
name = sys.argv[1]
todas_tabelas = sys.argv
#tabelas = sys.argv
print('create table ' + name +'(')
for n... |
import datetime
import calendar
def retirement(yearOfBirth, monthOfBirth):
age=67
month=0
yearOfBirth, monthOfBirth=int(yearOfBirth), int(monthOfBirth)
if yearOfBirth>=1900:
if yearOfBirth<=1937:
age=65
month=0
elif yearOfBirth==1938:
ag... |
my_dict = {"Knuth-Morris-Pratt" : "KMP" , "Mirko-Slavko" : "MS" , "Pasko-Patak" : "PP"}
print(my_dict)
x = my_dict.get("Mirko-Slavko")
print(x)
|
#!/usr/bin/python
m = int(input("Enter m: "))
x = (bytes.fromhex(format(m,'x'))).decode('utf-8')
print(x)
|
a = input().split()
b = input()
c = []
for idx, item in enumerate(a):
if item == b:
c.append(idx)
if len(c) == 0:
print("not found")
else:
for idx in c:
print(idx, end=" ") |
text = input()
def badpunc(text):
new_text = text.replace(',', '')
new_text = new_text.replace('.', '')
new_text = new_text.replace('!', '')
new_text = new_text.replace('?', '')
return new_text.lower()
print(badpunc(text)) |
n = int(input())
li = []
for i in range(n):
x = int(input())
li.append(x)
suma = float(sum(li))
mean = suma / n
print(mean) |
class Dictionary():
'''
Dictionary class takes a list as argument
and it has two methods
isWord(String) - Returns whether the given string exist in the dictionary.
isPrefix(string) - Returns whether the given string is a prefix of at least one word in the
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 23 12:42:33 2018
@author: bhuvan
"""
#Multiple Linear Regression
#sample model equation:
#y = B0 + B1 * X1 + B2 * X2 .... + Bn * Xn
#importing libraries
import numpy as np
import matplotlib.pyplot as plot
import pandas as pd
#importing the dataset
dataset = pd.read_csv... |
from turtle import *
Tahleek = Turtle()
Tahleek.color('orange')
Tahleek.pensize()
Tahleek.speed(3)
Tahleek.shape('turtle')
Tahleek.turtlesize(2,2,2)
def drawTriangle():
for x in range(3):
Tahleek.forward(80)
Tahleek.left(120)
for x in range(12):
drawTriangle()
Tahleek.left(30)
mainloop() |
import os
import time
os.system ("sudo pigpiod")
time.sleep(1)
import pigpio
ESC1 = 6
ESC2 = 5
pi = pigpio.pi()
pi.set_servo_pulsewidth(ESC1, 0)
maxVal = 2000
minVal = 500
print("Enter 'arm' to start the motors")
def control():
time.sleep(1)
speed = 1500
print("a -- decrease speed && d... |
with open('data.txt','r') as f:
data = f.readlines()
#print(data)
first = data[0]
print(first)
for i in data:
if len(i) > len(first):
maxx = i
print(maxx) |
class TileGrid:
def __init__(self, nrows, ncols, tiles):
"""
Create a TileGrid.
:param nrows: The number of rows in the map of tiles.
:type nrows: integer.
:param ncols: The number of columns in the map of tiles.
:type ncols: integer.
:param tiles: The arra... |
from probability import inverse_normal_cdf
from probability import normal_cdf
from typing import Tuple
import math
def normal_aproximation_to_binomial(n: int, p: float) -> Tuple[float, float]:
""" Returns mu and sigma corresponing to a Binomia(n, p) """
mu = p * n
sigma = math.sqrt(p * (1 - p) * n)
re... |
'''
Created on 15-Apr-2020
@author: ila roy
'''
#DSA-Assgn-18
def find_unknown_words(text,vocabulary):
#Remove pass and write your logic here
text_list=text.split(" ")
unknown_words_list=[]
for i in text_list:
if i not in vocabulary:
unknown_words_list.append(i)
i... |
# Given a non-negative number represented as an array of digits,
# add 1 to the number ( increment the number represented by the digits ).
# The digits are stored such that the most significant digit is at the head
# of the list.
# Example:
# If the vector has [1, 2, 3]
# the returned vector should be [1, 2, 4]
# as 1... |
################################################################################
# Kaya: Mumbling
#
#This time no story, no theory.
# The examples below show you how to write function accum:
# Examples:
# accum("abcd") # "A-Bb-Ccc-Dddd"
# accum("RqaEzty") # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
# accum("cwAt") ... |
print("Hello")
'''
arr = [10, 5, -2]
results = [10, 5]
arr = [10, 5, 2, -7, 15]
i
stack = [ 10]
result = [10, 15]
'''
def collisions(arr):
result = []
#iterate array
for i in range(0,len(arr)):
j = i+1
while arr[i] :
#compare values
#if absolute value of... |
#simple shiiping order system
#takes the number of orders and prints the cost
username = input("Hello, What is your username? ")
print("Hello {}, Welcome back.".format(username))
print("These are the current shipping rates: ")
rates = [5.10,5.00,4.95,4.80]
def print_shp_rates(rates):
print("To ship 0 t... |
#multiplaction/exponent table
number = float(input('Enter a number you want the exponent/multiplication table of :'))
def mult(number):
print('Multiplication Table')
for i in range(1,10):
mult = (number * i).__round__(2)
print('{} * {} = '.format(number,i),mult)
print('\n')
def e... |
"""Implement trigrams algorithm to create new text.
Use trigrams algorithm to randomly generate text based on an
an input text file, and given a number of words to generate.
"""
from random import sample
import sys
def read_book_from_file(book):
"""Take a .txt file and read it into a string."""
with open(boo... |
"""
To calculate the attack of a player in Tibia
Formula:
PS: This formula is based in values observed.
Max damage:
Where:
0.85*d*x*y + lvl/5
x = Weapon Attack
y = Player Skill
lvl = Player Level
d = Posture
Let's take an example of a 80 level player, using a 50 attack weapon, skills 85 and with attack p... |
"""
Lists
Lists in Python work like vectors (arrays) ins another languages, with the difference
of being dynamic and also receiving any type of data.
Language C/Java Arrays
- Have a fixed data type;
If you create an array int type, this arrays will always have
the int type and will have max 5 values.
P... |
""""
You are going to split the prize of 780.000 between 3 persons.
The first person gets 46%
The second person gets 32%
The third person gets the rest of it
"""
prize = 780000
fp = int(prize * .46)
sp = prize * .32
tp = prize * .22
print(f'The first person gets {fp}, The second person gets {sp}, The third pers... |
"""
String Type
In Python a data is a string type when:
Is between simple quotation marks -> 'A string', '234', 'a', 'True' '42.3'
Is between quotation marks -> "A string", "234", "a", "True" "42.3"
Is between triple simple quotation marks -> '''A string''', '''234''', '''a''', '''True''' '''42.3'''
"""
# Is between ... |
"""
Take a number and print the first N even numbers.
"""
print('Please input a number of odd numbers you want:')
n = int(input())
for even in range(0, n*2, 2):
print(even)
|
"""
Receive a number and verify if it's even or odd.
"""
print('Insert the number')
num = int(input())
if num % 2 == 1:
print('The number is odd')
else:
print('The number is even')
|
"""
Make a program to turn a uppercase letter in to a lowercase letter.
"""
print('Insert a word')
word = input()
print(word.swapcase())
|
"""
Calculate the sum of the first 50 even numbers.
"""
qty = 0
list0 = []
list1 = []
print('Please input a number of even numbers you want:')
n = int(input())
nl0 = int(n * 2 + 1)
print(nl0)
# while qty == 0:
# list0 = list(range(1, 101))
# list1 = sum(list0[1:50])
# qty += 1
# print(list1)
list0 = li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.