text stringlengths 37 1.41M |
|---|
#Faça um programa que leia três valores que representam os
#lados de um triângulo. Primeiramente, verifique se os lados podem formar um
#triângulo ( a soma de dois lados não pode ser menor que o terceiro lado ).
#Caso possa formar um triângulo, indique se este é equilátero, isósceles ou escaleno.
l1,l2,l3 = fl... |
import re
from CONFIGURATION import *
from hasher import *
print("\nWhat to encrypt? (Only lowercase letters and spaces)\n\n")
msg = input()
print("\nChoose a secure encrytion key: (min 8 caracters for security)\n\n")
securecode = input()
msg = msg.lower()
msg = re.sub(r'[^a-z ]', '', msg)
def splitter(s, n):
for... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from decoder import Signal
class Clustering:
"""
A machine learning algorithm that uses unsupervised learning processes in order to determine clusters.
"""
_kmeans: KMeans
_prediction: list
_n_clusters: int ... |
class MaxHeap:
# the constructor creates Heap
def __init__(self, items):
self.heap = [0]
for i in items:
self.heap.append(i)
self._heapify(len(self.heap) - 1)
# The push fucntion appends the element to the end of the heap and then floats it up to the right position
... |
i = 1
f=0
step=0
c = 'Ответ:'
print("Введите количество билетов")
k=int(input())
print("Введите номера билетов")
for i in range (k):
q=str(input())
if q[0] == 'a' and q[4] == '5' and q[5] == '5' and q[6] == '6' and q[7] == '6' and q[8] == '1':
c = c + ' ' + q
else:
f = f + 1
step = step ... |
a, b, c, x1, y1, x2, y2, y3, x3, p, S = float;
print(" 1- ,2- :");
v=int(input())
if (v = 1):
print(" a,b,c")
a=float(input(" a = "))
b=float(input(" b = "))
c=float(input(" c = "))
p = (a + b + c) / 2;
S = sqrt(p * (p - a) * (p - b) * (p - c));
print("S=",S)
else:
print(... |
class Book:
def __init__(self, title, num_of_pages, pub_year):
self.title = title
self.num_of_pages = num_of_pages
self.pub_year = pub_year
def __str__(self):
return self.title + ", " + str(self.num_of_pages) + " pages, " + str(self.pub_year)
def get_title(self):
... |
#class A: 는 class A(object): <-- object가 생략되어있는것이다. 모든 클래스는 object클래스를 상속받은 것이다.
class A:
pass
class SubA(A):
pass
### 부모꺼 super
#직원 관리 name, 급여, age
class Employee : #(object) <<생략되어있음.
def __init__(self, name="박채언", salary=2000000, age=26):
#super.__init__()생략되어있음.
self._name... |
#imports wordlist.py
import wordlist
#gets the word from wordlist.py at random
def get_word():
word=wordlist.get_random_word()
return word.upper()
#adds spaces to the word obtained from wordlist.py
def add_spaces(word):
word_with_spaces=" ".join(word)
return word_with_spaces
#draws the s... |
from replit import clear
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
##Calculate point amount
def calculate_score(hand):
"""take list of card within hand, and return score"""
if sum(hand) == 21 and len(hand) == 2:
return 0
if 11 in hand and sum(hand) > 21:
hand.remove(11)
han... |
recipes = {
'sandwich': {
"ingredients": ["ham", "bread", "cheese", "tomatoes"],
"meal": "lunch",
"prep_time": "10"},
'cake': {
"ingredients": ["flour", "sugar", "eggs"],
"meal": "dessert",
"prep_time": "60"},
'salad': {
"ingredients": ["avocado", "aru... |
class Evaluator:
def zip_evaluate(coeffs, words):
if len(coeffs) != len(words):
return (-1)
result = 0
for a, b in zip(words, coeffs):
result += len(a) * b
return result
def enumerate_evaluate(coeffs, words):
if len(coeffs) != len(words):
... |
# Word Ladders!!!!
# CC, 2017
from copy import copy
all_words = {}
f = open('words.txt')
# Fill all_words with words
for word in f:
word = word.strip()
all_words[word] = 0
start_word = raw_input("Start word: ")
end_word = raw_input("End word: ")
paths = {word: [] for word in all_words}
to_visit = {start_wo... |
#!/usr/bin/env python3
'''
create class
person
hass attribute age
check if value of age small than 18 raise error
"Sorry you age is below eligibility criteria"
use-> @property, @age.setter and make age private prop
'''
class Person:
def __init__(self,age):
self.... |
import re
match = re.search(r'PY.*N', 'PYANBNCNDN')
#贪婪匹配:默认返回匹配最长的字符串
print (match.group(0))
match1 = re.search(r'PY.*?N', 'PYANBNCNDN')
#最小匹配:默认返回匹配最短的字符串
print (match1.group(0)) |
def get_temp(temp, grad1, grad2):
'''
Aceasta functie face conversia gradelor, spre exemplu din grade Kelvin in grade Celsius si vice versa.
Functia face conversia si daca a fost introdus aceelasi grad, adica din C in C.
:param temp: temperatura ce trebuie convertita
:param grad1: unitatea de masura... |
from math import pi, sqrt
import numpy as np
def get_stockpile_volume(height, core_length):
"""
Compute the volume of a stockpile given the height and core length
:param height: stockpile height
:param core_length: stockpile core length
:return: stockpile volume
"""
return pow(height, 2.0... |
"""
CONSOLE LOGGING VERBOSITY LEVELS
---------------------------------
0 - FATAL
1 - CRITICAL
2 - INFO
3 - LOUD
4 - DEBUG
"""
from __future__ import print_function
#import warnings
VERBOSITY = 3
#warnings.simplefilter('always', UserWarning)
def print_divider(size):
if size == "large":
print("===========... |
nums = [3, 6, 15, 43, 50]
def process(num):
if num % 3 == 0 and num % 5 == 0:
print('FizzBuzz', num)
elif num % 3 == 0:
print('Fizz', num)
elif num % 5 == 0:
print('Buzz', num)
else:
print(num, 'not divisible by 3 or 5')
for num in nums:
process(num)
|
numbers = [1, 6, 8, 1, 2, 1, 5, 6]
n = int(input("Enter a number?"))
num = numbers.count(n)
print(n," appears {} times in my list".format(num)) |
sheep_sizes = [5,7,300,90,24,50,75]
print("Hello, my name is Thu and these are my sheep sizes", sheep_sizes)
for i in range (1,4):
print("MONTH", i)
new_sheep_sizes = [x+50 for x in sheep_sizes]
print("One month has passed, now here is my flock", new_sheep_sizes)
print("Now my biggest sheep has size... |
from turtle import *
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
shape("turtle")
speed(-1)
turtle_color = 0
for i in range(3,8):
for j in range(i):
forward(100)
left(360/i)
color(colors[turtle_color])
turtle_color+=1
mainloop() |
import eval
x = int(input("x = "))
operation = input("Operation(+,-,*,/):")
y = int(input("y = "))
res = eval.cal(x, y, operation)
print("* " * 20)
print( "{0} {1} {2} = {3}".format(x, operation ,y, res)) |
import socket
import sys
import threading
# server listens to everything happening on the port, when client and server both connected
# they'll be able to communicate and send data
class Client:
def __init__(self, conn):
threading.Client.__init__(self)
self.conn = conn
def run(self): # showi... |
def isNotPrime(x):
if x < 4:
return False
if x % 2 == 0:
return True
for div in range(2, x):
if x % div == 0:
return True
return False
def findM(n, m):
prime = n * m + 1
if isNotPrime(prime):
return m
return findM(n, m+1)
n = int(input())
print(f... |
size = int(input())
array = input().split()
index = 0
while index < len(array):
if array[index] in array[index+1:len(array)]:
array.pop(index)
else:
index+=1
print(len(array))
string=""
for j in range(0, len(array)):
string+= str(array[j])+" "
print(string)
|
greg_please = []
greg_input = 0
while greg_input >= 0 :
greg_input = eval(input("Input some numbers (-999 to exit): "))
greg_please.append(greg_input)
if greg_input == -999:
break
greg_please.remove(-999)
print ("of the numbers you input: ", greg_please )
greg_avg = sum(greg_please) / len(gr... |
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin': 42, 'rope': 1}
# dragon_loot のアイテムがinv内に存在するか確認し、存在していたら+1する
def add_to_inventory(inventory, added_items):
for i in range(len(added_items)):
item_name = added_items[i]
item_total = 0
if item_name in ... |
from math import sqrt, pow
class Kvec(object):
def __init__(self, points):
self.points = [point for point in points]
def __iter__(self):
return iter(self.points)
def __add__(self, other):
added = [x + y for x, y in zip(self.points, other.points)]
return self.__class__(adde... |
import random
import os
os.system('clear')
i = input("How many times to shuffle?: ")
d = input("How many cards to draw?: ")
draw_amnt = int(d)
times = int(i)
#shuffling mechanic
def shuffle(deck, times):
for y in range(0, times):
random.shuffle(deck)
print('Shuffled one more time')
#drawing mechanic
def dr... |
from turtle import Turtle
import random
colors = ['red', 'yellow', 'green', 'blue', 'cyan', 'magenta', 'teal', 'brown']
class Car(Turtle):
def __init__(self):
super().__init__()
self.shape('square')
self.penup()
self.shapesize(stretch_len=2, stretch_wid=1)
x = random.randi... |
while True:
try:
value=int(input("Enter a number between 1 and 10 : "))
except :# ValueError:
print ' You must enter a value between 1 and 10'
print'===========RESTART==============='
else:
if(value>0) and (value<=10) :
... |
user = {"name": "磯野", "age": 18, "job": "会社員"}
for k, v in user.items():
print("keyword:", k)
print("value:", v)
|
num = 44
if (num % 2) == 0:
print ("Chotnooe")
else:
print("Nechotnoe") |
def list_benefint():
listOfStrgs = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
return listOfStrgs
var = list_benefint()
print var
def sentence(info):
return "%s is a benefit of functions!" %info
print sentence("Bla")
def na... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 10 12:10:36 2018
@author: Admin
"""
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and ... |
for i in x:
pass
while ehto:
pass
for i in x:
if i == "a":
break
else:
# tähän tullaan jos x ei sisältänyt a:ta
print("ei a:ta")
# saman voi kirjoittaa myös:
if a not in x:
print("ei a:ta")
# tulostaa kaiken paitsi pienet kirjaimet
for i in "AArghKDJ!":
if i.islower():
continue
print(i)
# ikuinen silmu... |
def runTest():
pass
def hashChars(a,b):
if a > b:
return a+b
else:
return b+a
def findSubstring(input):
longest = "" #substring longest
current = "" #substring current
#dictionary of characters in current substring and last index position
charSet = {}
maxCharSet = 2
# Loop over input characters
for ... |
#!/usr/bin/env python
import nltk
from nltk.corpus import brown
# Write a program to find all words that occur at least three times in the Brown Corpus.
def many_words(corpus, number):
fdist = nltk.FreqDist([w.lower() for w in corpus])
words = [' ']
for word in fdist:
if fdist[word] >= number:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Title: Combine files
usage: combine_files.py [-h] [-o OUTDIR | -d] [-f FILEOUTNAME] dir type
Given files of a specified type, their text is combined into one file.
positional arguments:
dir directory which contains files
type t... |
"""
the cmax function that calculates the makespan of a given solution
the parameter solution is a numpy array object
ex :
[[ 4 8 8 7 2 3 29]
[ 9 4 5 8 6 2 32]
[ 5 9 8 10 1 0 33]
[ 9 3 10 1 8 1 31]]
"""
def cmax(solution, nb_machines):
nb_jobs = len(solution)
if nb_jobs == 0 or nb_mach... |
import random
from turtle import Turtle, Screen
my_screen = Screen()
my_screen.setup(600, 600)
user_bet = my_screen.textinput('Make your bet', 'Which one is the winner? Type your answer: ')
colors = ['yellow', 'black', 'orange', 'red', 'maroon', 'blue', 'purple']
y_position = [-200, -150, -100, 0, 100, 150, 200]
turtl... |
import tkinter
from tkinter import END
from tkinter import messagebox
import random
import pyperclip
# TODO: 2.Password generator
letters = ['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... |
# 컴퓨터 내부에서 재귀 함수의 수행은 스택 자료구조를 이용한다.
# 함수를 계속 호출했을 떄 가장 마지막에 호출한 함수가 먼저 수행을 끝내야 그 앞의 함수 호출이 종료되기 때문이다.
# 재귀 함수는 내부적으로 스택 자료구조와 동일하다는 것을 기억하자.
# 반복적으로 구현한 n!
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
# 재귀적으로 구현한 n!
def factorial_recursive(n... |
"""
Algoritmo de intercambio de claves de Diffie-Hellman:
p: número primo aleatorio
α: Entero ϵ [2,..., p-2]
a: valor aleatorio elegido por A (=K_privada_) ϵ [2,..., p-2]
K_publicaA_ = (α^b)^a mod p
b: valor aleatorio elegido por B (=K_privada_) ϵ [2,..., p-2]
K_publicaB_ = (α^a)^b mod p
A y B intercambian sus K_publ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import sympy
import hashlib
import string
class UOCRandom:
"""
Example:
>>> rnd = UOCRandom()
>>> rnd.get(1, 100)
7
>>> rnd = UOCRandom()
>>> rnd.get(1, 100)
7
Example with seed:
>>> rnd = UOCRandom(7)
>>> rnd.ge... |
import turtle
import pandas as pd
screen=turtle.Screen()
# code for map
screen.title("U.S states game")
image="blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data=pd.read_csv("50_states.csv")
all_states=data["state"].to_list()
guessed_states=[]
# code for user input
while len(guessed_s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def sqeq ( a=1.0, b=1.0, c=0.1 ) :
try :
D = b*b - 4*a*c
if D < 0 :
return []
else :
x1 = ( -b + math.sqrt( D ) )/(2 * a)
x2 = ( -b - math.sqrt( D ) )/(2 * a)
return [ x1, x2 ]
exc... |
import os
from urllib import request
from urllib.error import HTTPError
class Downloader:
file_path = ""
def __init__(self, file_name):
self.file_name = file_name
def create_directory(self):
directory_name = "images"
directory_path = os.path.join(os.getcwd(), directory_name)
if not os.path.exists(dir... |
#!/usr/bin/python
import argparse
def find_max_profit(prices):
max = -100000
for m in range(len(prices)-1):
for s in range(m+1, len(prices)):
if prices[s] - prices[m] > max:
max = prices[s] - prices[m]
print(prices[s], '-', prices[m], '= ', max)
... |
class GameView:
def __init__(self):
self.map = [
[2, 0, 0, 2],
[4, 2, 0, 2],
[2, 4, 2, 4],
[0, 4, 0, 4],]
self.__controller=GameController()
def move_left(self):
for line in self.map:
self.__controller.merge(line... |
# # Operatory porównujące
# # Przyrównanie ==
przypisanie = 2
przyrownanie = 2
print(przypisanie)
print(przyrownanie == przypisanie)
# # Wartości Boolowskie: True, False
#
# #Kilka przykładów porównań:
print("2==2: ", 2 == 2)
print("2==2.: ", 2 == 2.)
#
# #Priorytetyzacja operatorów (arytmetyczna vs porówn... |
def mysplit(strng):
myList = []
fnd = strng.find(' ')
start = 0
while fnd != -1:
if strng[start:fnd] != '':
myList.append(strng[start:fnd])
start = fnd + 1
fnd = strng.find(' ', fnd + 1)
if strng[start:fnd] != '':
myList.append(strng[start:]... |
### Wybrane zadania z testu końcowego
lista=[x*x for x in range(5)]
def fun(lst):
del lst[lst[2]]
print(lst)
print(lst[2])
print(len(lst))
return lst
print(fun(lista))
# Pytanie ...
def fun(x, y):
if x == y:
return x
else:
return fun(x, y - 1)
print(fun(... |
#!/usr/bin/env python3
import random as rnd
A = 'A'
a = 'a'
class Population(object):
def __init__(
self,
number,
init_fraction_recess,
weight_recess,
dominant_addition_per_generation,
):
if dominant_addition_per_generation > number:
raise ValueErr... |
#testing the concept
import re
#file_name = raw_input("Enter textfile name (ex. hamlet.txt): ")
def app(f_name):
fd = open(f_name, 'r')
fd = fd.read()
lines = fd.split('\n')
c1 = 0
while(c1 < len(lines)):
#lines[c1] = re.sub('[^0-9a-zA-Z]+', '', lines[c1])
if len(lines[c1]) == 0:
... |
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''UPDATE EMPLOYEE SET AGE = AGE+1 WHERE SEX = 'M' ''')
cursor.execute('''SELECT * FROM EMPLOYEE''')
result = cursor.fetchall();
print(result)
conn.commit()
conn.close() |
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 13:58:52 2018
@author: Mike
"""
import numpy as np
from collections import defaultdict
# define a graph class to store graph
class Graph:
def __init__(self,vertices):
self.V = vertices
self.graph = defaultdict(list)
... |
# link - https://www.hackerrank.com/challenges/py-collections-namedtuple/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
N , entry = int(input()) , namedtuple("Entry", input())
marks = [int(entry(*input().split()).MARKS) for _ in range(N)]
print(sum(mark... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations
string, n = input().split()
perm = [''.join(x) for x in permutations(sorted(string),int(n))]
print(*perm, sep='\n')
|
import distance
class ColNormInfo:
"""
Class to keep the normalization information
"""
def __init__(self, col_name, distance_fcn=distance.levenshtein,
threshold=None):
"""
Constructing column information
:param col_name: name of column
:param distance... |
import abc
class Controller(abc.ABC):
@abc.abstractmethod
def __init__(self):
"""Set up attributes and create data_out_queue"""
pass
@abc.abstractmethod
def register_sensor(self, sensor, name) -> bool:
"""Register a sensor in the sensor dict"""
pass
@abc.abstractmethod
def receive_data(self, data, de... |
'''
if문의 형식
: Java와 동일하지만 여러개의 조건이 필요할때는
else if가 아닌 elif를 사용한다.
형식]
if 조건1 :
실행문1
elif 조건2 :
실행문2
else :
실행문3
'''
age = 33
#여러개의 print()를 사용할때 한줄로 출력하고 싶다면 end=""룰 사용한다.
print(age, "살은 ", end="")
if age >= 35:
print("중년입니다.")
elif age >= 30... |
# method 1
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
def average_finder(*arg):
average = []
for i in zip(*arg):
average.append(sum(i)/len(i))
return average
print(average_finder(a,b,c))
# method 2
z =lambda *arg : [sum(i)/len(i) for i in zip(*arg)]
print(z(a,b,c))
|
print("Hi!!! I\'m Prashant")
user =input("what is your name:-")
print(f"hey!!! {user}, Nice to meet you.\nplease help me to choose me a pet animal")
dog=(" o____\n ||||")
sheep= ("o-###-\n | |")
please ={1:dog,2:sheep}
for key,value in please.items():
print(f"{key}:{value}")
help=int(input("please help:-"))
if h... |
first_name = input("enter yor first name :- ")
last_name = input("enter your last name :- ")
full_name = first_name.title() + " " + last_name.title()
print(full_name)
|
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.shape("circle")
self.penup()
self.x_move=10
self.y_move=10
self.movespeed=0.1
def move(self):
new_x=self.xcor()+self.... |
import numpy as np
import matplotlib.pyplot as plt
def main():
rows = input("Please enter the number of rows: ") # asks the user for number of rows
try :
rows = int(rows) # checks for a valid input
except ValueError:
rows = validChoice(rows)
columns ... |
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
d... |
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z |
"""Library to calculate costs and issue charge."""
# TODO comments require action.
# Other files of interest: models.py, cost_calc_test.py
from models import Dog, Customer
# Cost per pound by recipe.
RECIPE_COST_PER_POUND = {
'pork': 1.25,
'chicken': 1.49,
}
# Calories per pound by recipe.
CALORIES_PER_POUND = {
... |
from game.jumper import Jumper
from game.player import Player
from game.puzzle import Puzzle
from game.console import Console
class Director:
"""A code template for a person who directs the game. The responsibility of
this class of objects is to control the sequence of play.
Stereotype:
Contr... |
list_item = [6, 2, 3, 5, 7, 33, 1, 44, 55, 11, 67, 90] # Исправил
def min_item_square(item_list): # O(n^2) квадратичная
number_result = 99999999999999999
for itm in item_list: #O(n)
for itm2 in item_list: #O(n)
if (it... |
class SocketRunningException(Exception):
"""
A Socket exception thrown when the socket is already running
"""
def __init__(self, message):
super().__init__(self)
self.message = message
def __str__(self):
return repr(self.message)
|
import csv
import pandas as pd
eFileName = './employee_file.csv'
class Employee:
def __init__(self,eFirstName,eLastName,eID,eCNIC,ePhoneNumber):
self.empFName = eFirstName
self.empLName = eLastName
self.empID = eID
self.empCNIC = eCNIC
self.empPhone = ePh... |
import csv
import pandas as pd
bFileName = './book_file.csv'
bTitle = str(input("please enter book title:\n"))
bAuthor = str(input("please enter book author:\n"))
bISBN = str(input("please enter book ISBN:\n"))
with open(bFileName, mode='a') as csv_file:
fieldnames = ['Title', 'Author', 'ISBN']
... |
def play_nimsticks():
# Load in your initial board_state here.
board_state = "Some board state."
# Here we set up switches to swap the players.
ply1 = True
ply2 = False
# Next we have a while loop until the board_state is equal to [].
while board_state:
# Check for terminal bo... |
import re
count=0
text=input("Enter your text:")
word=input("what is the word you wanna search:")
pattern=re.compile("word")
match=pattern.finditer("text")
for i in match:
count=count+1
print("jai word is existed for",count,"times")
|
n=int(input("Enter a integer:"))
sum=0
while n>0:
r=n%2
sum=sum+r
n=n//10
print(sum) |
def account():
acno=int(input("Enter account number:"))
name=input("Enter your name:")
curr_balance=float(input("Enter your current balance:"))
transact_amount=float(input("Enter your transaction amount:"))
transact_code=input("Enter your transact code")
if(transact_code=='d'):
print(nam... |
Bank_names=['HDFC','ICICI']
account_numbers_HDFC=range(11223345,55667789)
account_numbers_ICICI=range(4455667789,5566778900)
account_types=['savings','current','fixed']
cus_bank_name=input("Dear customer,Enter your Bank name:")
cus_account_number=int(input("Dear customer,Enter your account number:"))
cus_account_type=i... |
file_name=input("Enter file name:")
file_mode=input("Enter the mode of your choice (w/r/a/r+/w+/a+) :")
f=open(file_name,file_mode)
eno=input("Enter employe ID:")
ename=input("Enter employee name:")
edept=input("Enter employee department:")
edesg=input("Enter employee designation:")
esal=input("Enter employee salary:")... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 24 10:23:39 2019
@author: jaideep
"""
car_prices=eval(input("Enter car prices:"))
discountset=set()
for i in car_prices:
discount=i*(20/100)
discountset.add(discount)
print(discountset)
|
f=open("Employee.txt",'w')
"""
open function is used to open the file in specified mode
e.g; in the above line open function is used to open employee.txt file in 'w' mode
open() : open function performs two responsibilities
1.if file is existed it opens the existed file in specified mode.
2.if file is not existed it c... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 17 16:03:34 2019
@author: jaideep
"""
company_names=eval(input("Enter ur company names:"))
print("@"*30)
print("Company names are :",company_names)
ans="YES"
while ans=="YES":
existed_company=input("After which company u want to add the new company name :")
i=com... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 17:27:40 2019
@author: jaideep
"""
class product:
def product_info(self):
self.product_ID = input("Enter product ID :")
self.product_name = input("Enter the product name :")
self.product_company= input("Enter the product company:")
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 1 15:16:35 2019
@author: jaideep
"""
# WITH EXCEPTION
a=10
b=0
try:
print("Division:",a/b) #execption causing line or problematic line
except ZeroDivisionError: #Named except block
"""
@ Named execption can only handle that named exception only.
"""
print("A ... |
"""
Module implementing various activation function in neural network
"""
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def relu(x):
return np.maximum(0, x)
def softmax(x, axis=None):
return np.exp(x) / sum(np.exp(x))
class Sigmoid():
def __init__(self):
pass
def __cal... |
#! /usr/bin/env python
from mrjob.job import MRJob
class MRMoviesByGenreCount(MRJob):
"""
Find the distinct number of movies in each genre.
"""
def mapper(self, _, line):
"""
Implement your mapper here!
Don't forget that we don't care about movies that don't have a genre
... |
# example of exercise 5 for lesson 15
print("Enter the filename : ")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
# study drill 7
txt_again.close() |
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs *= 5
# short hand way of writing dogs + 5
# thi... |
# Exercise 13: Parameters, Unpacking, Variables
"""
now we will cover another input method that you can use to pass variables to a script
script = another name for .py files
we have typed python3.6 LPTHW.ex13.py to run the LPHTHW.ex13.py file
the LPTHW.ex13.py part of the command is called an "argument"
now we are go... |
print "Mary had a little lamb."
print "Its fleece was white as %s" % 'snow'
print "And everywhere that Mary went."
#Prints this statement 10 times
print "." * 10
#Assigns each variable to a string of one
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end... |
print "You enter a dark room with three doors. Do you go through door #1, door #2 or door #3?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating cheese cake! What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "T... |
from math import sqrt
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
def removeStopwords (phrase):
noStopwords = []
for word in phrase:
if word not in stopwords:
noStopwords.append(word)
return noStopwords
def stemmingPhrase (phrase):
stemmed = []... |
# Python CeaserPigLatin Encryption
# Trey Hall
# 9/17/18
consonants = [ 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z']
vowels = ['A','E','I','O','U',]
def letter_is_vowel (letter):
is_vowel = -1
# begin a loop through the vowel array
for current_letter in ... |
from math import exp, log
"""
Units
- Absolute humidity: g/kg
- Relative humidity: between 0 and 1
- Temperature: Celsius
"""
def saturation_ah(t: float) -> float:
# Ref: https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
c = 6.112 * 18.02 / 0.08314
c =... |
def sub_downcase(text, from_text, to):
result = ""
for i in range(from_text, to):
result += text[i].lower()
return result
def match(text, subtext = ""):
result = []
if(len(subtext) == 0) or (len(text) < len(subtext)):
return "<no matches>"
_end = len(text) - len(subtext) + 1
... |
from hashlib import sha256
print("Welcome to the program which memorises your comments.")
mypassword = "219aeb43c0cc62089487cc77c6603b760edac4d616186e6fea5d0aa8122f49c2"
#Password Protection has been taken from this link:
#https://bitbucket.org/damienjadeduff/hashing_example/raw/master/hash_password.py
def c... |
# Title Car Class
# Author: Benjamin Lemery
# Date: 11/11/19
# This program demonstrates how to use classes.
# README: Start the program from change-color.py and/or odometer_increment.py
class Car:
def __init__(self,make,model,color,year,price,mileage):
self.make = make
self.model = model
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.