text stringlengths 5 121k |
|---|
antiguedad=5
sueldo=300
if antiguedad>5:
print(sueldo*1.2)
if antiguedad<=5 and antiguedad>1:
print(sueldo*1.1)
else:
print(sueldo)
control1=int(input("ingrese el primer peso"))
control2=int(input("ingrese el segundo peso"))
control3=int(input("ingrese el tercer peso"))
if control2-control1<300... |
num1=int(input("ingrese un numero menor que 1000: "))
num2=int(input("ingrese otro numero menor que 1000:"))
if num1<1000 and num2<1000 :
a=int((num1/10)%10)
b=int((num2)%10)
c=int((num2/100)%10)
suma=a+b+c
union=(f"{a}{b}{c}")
print(f"el numero formado es: {union}")
print(f"la sum... |
import heapq as hp
def kLargest(arr, n, k):
q = []
for i in range(n):
hp.heappush(q, arr[i])
if len(q) > k:
hp.heappop(q)
q.sort(reverse=True)
return q[-1]
N = 7
K = 3
Arr = [1, 23, 12, 9, 30, 2, 50, 89]
print(kLargest(Arr, N, K)) |
def triplet(arr, n, k):
count = 0
for i in range(0, n-2):
for j in range(i+1, n-1):
for x in range(j+1, n):
if arr[i]+arr[j]+arr[x] == k:
return 1
return 0
def triplet(arr, n, k):
count = 0
arr.sort()
for i in range(0, n-... |
def heapify(arr, i):
largest = i
left = (2 * i) + 1
right = (2 * i) + 2
if left < len(arr) and arr[left] > arr[largest]:
largest = left
if right < len(arr) and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[largest], arr[i] = arr[i], arr[largest]
... |
from random import choice
from string import ascii_lowercase
KEY_LENGTH = 6
TXT = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"
C = [
"g:ydkzunydkzunydkzunydkzunydkz",
"h:zunydkzunydkzunydkzunydkzuny",
"f:xmhalqxmhalqxmhalqxmhalqxmha"
]
def gen_random_str(n):
return "".join(choice(ascii_lowercase) for _ in range(n))
def k... |
from datetime import datetime,timedelta
birthday = input('When is your birthday (dd/mm/yyyy)? ')
birthday_date = datetime.strptime(birthday, '%d/%m/%Y')
print('Birthday: ' + str(birthday_date))
one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday: ' + str(birthday... |
from datetime import datetime, timedelta
today = datetime.now()
print('Today is: ' + str(today))
one_day = timedelta(days=1)
yesterday = today - one_day
print('Yesterday was: ' + str(yesterday))
one_week = timedelta(weeks=1)
last_week = today - one_week
print('Last week was: ' + str(last_week))
|
total = 0
for day in range (1, 6):
print("Enter number of bugs collected on day", day)
bugs = int (input())
total = total + bugs
print("You have collected a total of", total, "bugs")
|
Prime1 = input("Enter first primary color of red, yellow or blue:")
Prime2 = input("Enter second different primary color of red, yellow or blue:")
if Prime1 == "red" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "red":
print("orange")
elif Prime1 == "blue" and Prime2 == "yell... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
movies = pd.read_csv("/home/wasi/ML_FOLDER/Udacity-DSND-master/Experimental Design & Recommandations/Recommendations/"
"1_Intro_to_Recommendations/movies_clean.csv")
reviews = pd.read_csv("/home/wasi/ML_FOLDER/Udacity-DSND-m... |
from tkinter import*
from tkinter import messagebox
def cancel():
messagebox.showinfo("Cancelled")
def display():
messagebox.showinfo("Registered")
window=Tk()
window.geometry("760x550")
window.resizable(width=0,height=0)
window.title("ADMISSION")
name=StringVar()
l1=Label(window, text="Student Admis... |
import sys
def medistance(source, target):
n= len(source)
m= len(target)
ins_cost=1
sub_cost=2
del_cost=1
D=[[0 for a in range(m+1)] for a in range(n+1)]
for i in range (0, n+1):
D[i][0]=i
for j in range (0, m+1):
D... |
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alicia', 'Bert', 'Czech', 'David'],
['Dogs', 'chicken', 'moose', 'goose']]
def printTable():
colWidths = [0] * len(tableData)
for i in range(len(tableData)):
for j in range(len(colWidths)):
curr = len... |
"""In the first line, print True if has any alphanumeric characters. Otherwise, print False.
In the second line, print True if has any alphabetical characters. Otherwise, print False.
In the third line, print True if has any digits. Otherwise, print False.
In the fourth line, print True if has any lowercase char... |
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one
possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are
listed numerically or alphabetically, we call it lexicographic order. The
lexicographic permutations of 0, 1 and 2 are:
012
021
102
120
201
210
What is th... |
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('Haarcascades/haarcascade_eye.xml')
image = cv2.imread('images/putin.jpg')
glass_img = cv2.imread('images/glasses2.png')
cv2.imshow('image',ima... |
def update(a):
print(id(a))
a=10
print(id(a))
print ('a',a)
def update1(a):
print(id(a))
a[1]=10
print(id(a))
print ('lst',a)
x=8
print(id(x))
update(x)
print ('x',x)
lst=[1,4,2,3]
print (id(lst))
update1(lst)
print('ls:',lst)
|
x=int(input("upto which fibonacci no's u want: "))
def fib(x):
a=0
b=1
if x<=0:
print('not possible')
elif x==1:
print(a)
elif x>=2:
print(a)
print(b)
for i in range(2,x):
c=a+b
if c<=x:
pri... |
a=10
print(id(a))
def some():
a = 23
x = globals()['a']
print(id(x))
print('inside:',x)
print('ins:',a)
globals()['a']=45
some()
print('outside:',a) |
from turtle import *
shape('turtle')
speed(0)
length = 10
for i in range (100):
forward(length)
length += 5
left(90)
mainloop()
|
from random import randint
x = randint(1, 100)
loop = True
while loop:
num = int(input("Enter a number 1 - 100: "))
if num == x:
print("Bingo")
loop = False
elif num < x:
print("A little too small")
else:
print("A little too large")
|
numbers = [1, 6, 8, 1, 2, 1, 5, 6, 1, 4, 5, 2, 7, 8, 4, 5, 9, 2, 1, 6, 8, 0, 0, 5, 6]
x = int(input("Enter a number? "))
count = numbers.count(x)
print(x, "appears " + str(count) + " times in the list")
|
COURSES = {
"Python Basics": {"Python", "functions", "variables",
"booleans", "integers", "floats",
"arrays", "strings", "exceptions",
"conditions", "input", "loops"},
"Java Basics": {"Java", "strings", "variables",
"inp... |
favorite_things = ['raindrops on roses', 'whiskers on kittens',
'bright copper kettles','warm woolen mittens',
'bright paper packages tied up with string',
'cream colored ponies', 'crisp apple strudels']
slice1 = favorite_things[1:4]
slice2 = favorite_things[5:]
sorted_thin... |
string = input().split()
numbers = [int(num) for num in string]
print(f"Sum of all numbers is {sum(numbers)}") |
def get_cs():
return input()
def cs_to_lot(string):
separated = string.split(';')
listOt = [tuple(i.split('=')) for i in separated]
return listOt
def lot_to_cs(listOfTuples):
string = ""
for (a, b) in listOfTuples:
string += a+"="+b+";"
return string
def display(l):
print(l... |
print("hello world")
y = 2.5
x,y, name, is_cool = (1,2.5,'john',True)
''' type casting '''
""" arguments by position """
name = 'may'
age=20
print('My name is {nm} & Im {yr} years old'.format(nm=name,yr=age))
|
"""
Created on Sat Nov 23 13:50:03 2019
@author: Nathan
"""
import sys
import serial_hash_search
import parallel_hash_search
PARALLEL = False
def read_text(file_name):
with open(file_name, 'r', encoding='utf-8') as file:
return file.read()
if __name__ == '__main__':
"""
Command line arguments... |
def areSimilar(a, b):
da = []
db = []
for i,n in enumerate(a):
if a[i] != b[i]:
da.append(a[i])
db.append(b[i])
return len(da) <= 2 and len(db) <= 2 and sorted(da) == sorted(db)
a = [1, 1, 4]
b = [1, 2, 3]
print(areSimilar(a,b)) |
def naturalNumbersListing(n):
s = 0
i = 1
t = 2
while i <= n:
s += i
if i < n: s += i + 1
i += t
t += 1
i += t
t += 1
return s
print(naturalNumbersListing(3)) |
import sys, cs50
if len(sys.argv) != 2 or sys.argv[1] not in ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin']:
sys.exit("Usage: python roster.py [house name] or there's no house name")
sys.exit(1)
db = cs50.SQL("sqlite:///students.db")
students = db.execute("SELECT * FROM students WHERE house = (?) ... |
import random
alphabet = "abcdefghijklmnopqrstuvwxyz1234567890"
VIDE, PION_BLANC, PION_NOIR, TOUR_BLANC, TOUR_NOIR, CAVALIER_BLANC, CAVALIER_NOIR, FOU_BLANC, FOU_NOIR, REINE_BLANC, REINE_NOIR, ROI_BLANC, ROI_NOIR = \
'O', 'P', 'p', 'T', 't', 'C', 'c', 'F', 'f', 'R', 'r', 'K', 'k'
def generate_random_name():
... |
def isOpener(chara, openers):
return (chara in openers)
def isCloser(chara, closers):
return(chara in closers)
def scopeCheck(scopeSequence, scopeMatch):
s = []
for x,chara in enumerate(scopeSequence):
print(chara)
if isOpener(chara, scopeMatch.values()):
print(... |
def sayHello():
print("Hello")
def sayIt(msg):
print(msg)
def add(n1, n2):
result=n1+n2
print(result)
sayHello()
sayIt("你好,python")
sayIt("第二次呼叫python")
add(3,5)
add(1000,18090) |
import sys
def montaMatriz(linhas,colunas):
matriz = [0.0] * linhas
for i in range(linhas):
matriz[i] = [0.0] * colunas
return matriz
def geraNumeros(vmin,vmax,linhas,colunas):
for x in range(vmin,(linhas * colunas),1):
print("x1 =",x)
def main():
dimension, interval, matrix, rows, cols, vmin, vmax, listaN... |
even=0
odd=0
a=[]
b=int(input("Enter no. of elements="))
for i in range(0,b):
t=int(input("Enter in list="))
a.append(t)
for i in a:
if(i%2==0):
even+=1
else:
odd+=1 |
fname = input("Enter file name: ")
fh = open(fname)
count = 0
tot = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
pos = line.find(' ')
num = line[pos:]
num = float(num)
count = count + 1
tot = num + tot
print(tot)
ans = tot / count
print("Average spam confidence:", ans)
|
'''
Team B2-4ac- Bayan Berri, Alessandro Cartegni
SoftDev1 pd7
HW03: StI/O: Divine your Destiny!
2017-09-14
'''
import random
def makedict(filename):
"""
makes a dictionary from csv file param
arg:
string filename csv file
ret:
dictionary d keys: jobs values: percents
"""
d = dict(... |
class Bank:
def rateOfInterest(self):
return 0
class ICICI(Bank):
def rateOfInterest(self):
return 10.5
if __name__ == '__main__':
b_Obj = Bank()
print(b_Obj.rateOfInterest())
class Cat:
def __init__(self, name):
self.name = name
def info(self):
print(f... |
username = input("Enter your name: ")
output_file = open("name.txt", 'w')
print("{}".format(username), file=output_file)
output_file.close()
open_file = open("name.txt", 'r')
print("Your name is {}".format(open_file.read()))
open_file.close()
number_file = open("numbers.txt", 'r')
first_number = int(number_file.r... |
class Student(object):
def __init__(self, __name, score):
self.__name = __name
self.score = score
def print_score(self):
print('%s %s' % (self.__name, self.score))
def get_name(self):
return self.__name
def set_name(self,name):
self.__name = name
bart = Stu... |
import itertools
cs = itertools.cycle('ABC')
for c in cs:
print(c)
|
import zipfile
import os
import shutil
def zip_directory(path):
zip_targets = []
base = os.path.basename(path)
zipfilepath = os.path.abspath('%s.zip' % base)
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
filepath = os.path.join(dir... |
import tkinter
window = tkinter.Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
my_label = tkinter.Label()
window.mainloop() |
year = int(input("Which year do you want to check? "))
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
if(year % 4 == 0) and ((not year % 100 == 0) or (year ... |
class Animal:
def __init__(self):
self.num_eyes = 2
def breathe(self):
print("Inhale, exhale.")
class Fish(Animal):
def __init__(self):
super().__init__()
def breathe(self):
super().breathe()
print("doing this underwater.")
def swim(self)... |
alphabet = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
]
def caesar(start_text, shift_amount, ... |
from cipherfunctions import caesar
from art import logo
print(logo)
should_continue = True
while should_continue:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(start_te... |
import random
import art
from os import system
from game_data import data
def choose_accounts():
return random.choice(data)
def format_entry(choice):
return f'{choice["name"]}, a {choice["description"]}, from {choice["country"]}'
def compare_accounts(player_choice, not_choice):
if player_choice["follow... |
import DecisionTree
import math
def DecisionTreeLearner(dataset):
def decisionTreeLearning(examples, attributes, parents_examples=()):
if len(examples) == 0:
return pluralityValue(parents_examples)
elif allSameClass(examples):
return DecisionTree.Leaf(examples[0][dataset.t... |
import smtplib
from email.mime.text import MIMEText
from email.header import Header
"""
We send email via SMTP(Simple Mail Transfer Protocol) and MIME(Multipurpose Internet Mail Extensions),
which require that both the sender and receiver should open his SMTP service.
Otherwise, the request for sending email will fai... |
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 5))
x = np.linspace(-50, 50, 1000)
plt.plot(x, (1+3*x), color='black')
plt.plot(x, (2-x)/2, color='blue')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Problem 3 A / B')
plt.show()
|
for i in range(1,10):
print("*************************")
for k in range(1,10):
print("{} x {} = {}".format(k,i,i*k)) |
import sys
import data
import classifiers
def main(argv):
'''Reads in a training set and a test set and builds two KNN
classifiers. One uses all of the data, one uses 10
exemplars. Then it classifies the test data and prints out the
results.
'''
if len(argv) < 3:
print('Us... |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def has_equal_num(s):
s = ''.join(sorted(s)).strip('.')
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
retu... |
from __future__ import division, print_function
def average(array):
"""
Compute the average of distinct items in an array.
Parameters
----------
* `array` [list]
array of potentially non-unique numbers.
Returns
-------
Mean of the unique elements in the array. [float]
"""... |
Week = ('Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday','Saturday','Sunday')
fruits = set(['apple', 'mango', 'orange'])
new_fruits = {'chery', 'peach','apple', 'mango'}
print(new_fruits.difference(fruits))
print(new_fruits.intersection(fruits))
|
list1 = list(range(5))
list2 = list1
list3 = list1[:]
list1.append(8)
list2.append(11)
list3.append(10)
print(list1)
print(list2)
print(list3)
|
from time import gmtime, strftime
def workWithString(name):
upper = name.upper()
length = len(name)
print("- WORK WITH STRING - " + name * 3)
print(upper)
print(length)
def workWithNumber(numbers):
print('- WORK WITH NUMBERS')
for number in numbers:
print(number)
if number... |
fstnumber = float(input("Introduce a number:"))
scndnumber = float(input("Introduce another number:"))
quotient = fstnumber//scndnumber
rest = fstnumber%scndnumber
print(f"Between {fstnumber} and {scndnumber} there's a quotient of {quotient} and a rest of {rest}") |
class Solution(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
width = 1
parents = [root]
stop = False
while not stop:
level = []
for pare... |
import os
import csv
csvpath = os.path.join("..", "Resources", "budget_data.csv")
total_months = 0
total_profit = []
monthly_profit_change = []
min=0
max=0
with open(csvpath, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csvheader = next(csvreader)
for row in csvreader:
... |
for i in range(2,10):
for j in range(1, 10):
print(i*j, end=" ")
print(" ")
a = [1,2,3,4]
result = [num * 3 for num in a if num % 2 == 0]
print(result)
a = [(1, 3), (2, 4), (3, 5)]
for (f, r) in a:
print(f + r)
marks = [90, 5, 67, 45, 80]
number = 0
for points in marks:
numbe... |
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def merge_linked_lists_recursively(node1, node2):
""""merge 2 sorted linked list into a sorted list (ascending)"""
if node1 == None:
return node2
elif node2 == None:
return node1
new_h... |
def produce_ugly_number_solution_1(n):
"""
produce the n-th ugly number by generating n ugly number
the ugly number next to K is some number prior to K times 2 or 3 or 5
"""
ls = [1]
k = 0
t2, t3, t5 = 0, 0, 0
for i in range(n - 1):
while 2 * ls[t2] < ls[i]:
t2 += ... |
def min_in_rotated_list(ls):
if ls == None:
return False
start = 0
end = len(ls) - 1
while ls[start] >= ls[end]:
if end - start == 1:
return ls[end]
mid_index = (start + end) >> 1
if ls[mid_index] == ls[start] and ls[mid_index] == ls[end]:
... |
import sys
def ROT(n):
text = sys.argv[1]
if sys.argv[3] == "+":
hasil = [chr(ord(i)+n) for i in text]
hasil1 = "".join(hasil)
return hasil1
elif sys.argv[3] == "-":
hasil = [chr(ord(i)-n) for i in text]
hasil1 = "".join(hasil)
return hasil1
for rot in range(... |
if __name__ == '__main__':
print("Escribe la cantidad invertida")
cantidad = float(input())
print("Escribe la tasa de interes")
tasa = float(input())
intereses = cantidad*tasa
if intereses>100000:
print("Los intereses ganados son $",intereses," superan los $100000")
else:
print("Los intereses ganados son $",... |
"""
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)
"""
TASK 3:
(080) is the area code for fixed ... |
"""
Created on Fri Sep 4 18:47:09 2020
@author: 16509
"""
input1=0
C=0
F=0
A=0
z=0
def display_menu():
input1=input("Indicate which temperature conversion you would like to perform, by entering 1 or 2,1. Fahrenheit to Celsius2. Celsius to Fahrenheit")
return input1
def convert_temp(A):
... |
import pandas as pd
array = {'A' : [1,2,3,4,5,4,3,2,1], 'B' : [5,4,3,2,1,2,3,4,5], 'C' : [2,4,6,8,10,12,14,16,18]}
df_array = pd.DataFrame(data=array)
print("Arranjo original")
print(df_array)
print("\n")
print("Removendo linhas cuja coluna B tenha valores iguais a 3")
df_array_new = df_array[df_array.B != 3]
prin... |
def main():
n = 40
print("this is a {}".format(n))
print('this is a {}'.format(n))
print('''this is a string
text
text
''')
if __name__=="__main__": main()
|
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_pointer = -1
two_pointer = len(nums)
i = 0
while i<two_pointer:
if(nums[i]==0):
if(i==zero_... |
from math import sqrt
print(" ----------Pythagoras Theorem to Find the sides of the Triangle---------- ")
print(" ------------ Enter any one side as 0 to obtain the result -------------- ")
base = int(input("Enter the base of the Triangle: "))
perpendicular = int(input("Enter the perpendicular of the Triangle:... |
class Book:
def __init__(self, name):
self.name = name
boo1 = Book('gggggggggggg')
strybook = Book('yyyyyyb hh')
pythonbook = Book('hey hello')
boo1.name = 'gggggggggggg'
strybook.name='yyyyyyb hh'
pythonbook.name = 'hey hello'
print(boo1.name)
print(strybook.name)
... |
try:
i = 1
j = 10/i
values = [1, '2']
sum(values)
except TypeError:
print('TypeError')
j = 10
except ZeroDivisionError:
print('ZeroDivisionError')
j = 0
except:
print('other error')
j = 5
else:
print('Else')
finally:
print('finally')
prin... |
import os
import sys
from pathlib import Path
dirs = {
'Web': ['.html', '.htm'],
'Zips': ['.exe', '.zip', '.rar'],
'Documents': ['.docx', '.doc', '.pdf', '.xls', '.odt'],
'Images': ['.jpg', '.jpeg', '.gif', '.bmp', '.png', '.psd', '.heif'],
'Videos': ['.mp4', '.avi', '.flv', '.mov', '.mpeg'],
... |
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv("KVIS student dataset.csv")
dataset.columns = ['thai', 'region', 'english', 'income', 'expense', 'students']
def show_plot(dataset, region = 'all', show_none = False):
__dataset = dataset
if s... |
arr=[1,2,3,4]
if arr[3]<arr[2]:
print(1 and 0 or 1)
else:
print(1 or 0 and 0) |
d1={'Canada':100,'Japan':200,'Germany':300,'Italy':400}
print("*"*10)
for x in d1:
print(x)
print ("*"*10)
for x in d1:
print(d1[x])
print ("*"*10)
for x in d1.values():
print(x)
print ("*"*10)
for x,y in d1.items():
print(x,"=>",y)
|
"""Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
return []
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print(quicksort(test)) |
a='1'
a=a*3
print(a)
b='44'
b=b*4
print(b)
|
x=2
for count in range(3):
x=x**2
print(x)
|
print(True or False)
print(True and False)
n=5
for level in range(1,n+1):
print(level * '*')
for level in range(1,n+1):
print(''*(n-level)+ level* '*')
print(len("Hello")+len("World"))
a={'d':3}
print(a.get('d'))
a['d']+=2
print(a.get('d')+3)
temp=35
if temp>30:
print("Hot!")
elif tem... |
height=float(input("Enter height of the person:"))
weight=float(input("Enter weight of the person:"))
bmi=weight/(height**2)
print("Your BMI IS:{0} and you are:".format(bmi),end='')
if(bmi<16):
print("severly underweight")
elif(bmi>=16 and bmi<18.5):
print("underweight")
elif(bmi>=18.5 and bmi>=25):
... |
num=[8,8,8,8]
x=1
for i in range (1,len(num)):
x=1
print(x) |
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print(f'Pssst, the solution is {chosen_word}.')
display=["_"]*len(chosen_word)
print(display)
print(chosen_word)
guess = input("Guess a letter: ").lower()
print("weong")
|
print('Welcome to the tip calculator')
bill = float(input('What was the total bill? $'))
tip= float(input('What percentage tip would you like to give? '))
people = float(input("How many people split the bill? "))
pay= bill*(1+tip/100)/people
pay=float(pay)
print("Each person should pay: $",round(pay,2))
|
import numpy as np
def find_duplicates(dataset, app_name_index,
tag, use_array=True):
"""Find duplicate app names"""
if use_array:
dataset = np.asarray(dataset)
app_names = dataset[:,app_name_index]
unique_apps = set(app_names)
duplicate_apps = len(dataset)... |
"""
Pygame 008
Description:
Writing out the new colors file
Randomly picking ball and screen colors
New Code:
None
"""
import pygame
import random
import json
import pprint
def fix_colors(infile):
""" One time fix of original json file with only names and hex values.
See previous lesson for... |
"""
Pygame 011
Description:
Fixing our Ball Class Part 2
New Code:
None
"""
import pygame
import random
import json
import pprint
import sys
def load_colors(infile):
with open(infile,'r') as f:
data = f.read()
colors = json.loads(data)
return colors
config = {
'title' :'006 Py... |
name = "NIKOLA TESLA"
quote = "The only mystery in life is: why did Kamikaze pilots wear helmets?"
print(name.lower())
print(name.upper())
print(name.capitalize())
print(name.title())
print(name.isalpha())
print(quote.find('Kamikaze'))
print(quote.find('Kamikazsdfe'))
new_name = input("Please enter a name:... |
import math
import os,sys
import json
class Data:
@staticmethod
def validJson(jdata):
try:
json_object = json.loads(jdata)
return True
except ValueError as e:
pass
return False
@staticmethod
def readJson(loc_path):
if os.path.isfil... |
"""
Pygame 005
Description:
Simple config starter
And drawing a ball
New Code:
- pygame.draw.circle(screen, (red, green, blue), (250, 250), 75)
"""
config = {
'title' :'005 Pygame Lesson'
}
colors = {
'magenta':(255, 0, 255, 100),
'cyan':(0, 255, 255, 100),
'background':(0,130,200,100)
... |
"""Techniques for inference.
Description
-----------
Inference is same as asking conditional probability questions to the models.
"""
from pgmpy.inference import VariableElimination
import bnlearn
import numpy as np
def fit(model, variables=None, evidence=None, to_df=True, verbose=3):
"""Inference using... |
import csv
def Reader(fileName):
file=open(fileName)
dicr=csv.DictReader(file)
for row in dicr:
size=[]
size.append(row['sq__ft'])
price=[]
price.append(row['price'])
return price,size
|
"""
Created on Wed Apr 17 13:33:52 2019
@author: emily.gu
"""
from mnist import MNIST
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.layers.advanced_activations import LeakyReLU
from keras.utils import to_categorical
fr... |
'''
Given a list of integers with no duplicates, find the max and set it as the root of a tree
The left subtree is then a tree built from the left partition of the list (list[0:max])
The right subtree is a tree build from the right partition of the remaining list (list[max+1:])
Return the root node
'''
class TreeNode... |
radius = int(input())
pi = 3.14159
volume = float(4.0 * pi * (radius* radius * radius) / 3)
print("VOLUME = %0.3f" %volume) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.