text
stringlengths
37
1.41M
import rimas as rimas class Verso: def __init__(self, body: str): self.body = body class Estrofe: def __init__(self, body: str): self.body = body def __repr__(self): return "represento isto: " + self.body @property def n_versos_label(self): n_versos = self.n_vers...
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from tkinter import * bot = ChatBot("Misty") conversation = [ "Hello", "Hi there!", "What is your name?", "my name is Misty, i am created by diksha.", "How are you doing?", "I'm doing great.", "That is good to hea...
""" *Given a list of Strings, and an external order in which it needs to be sorted, Sort the given list of *strings. * *For example: *Input Strings : "Ajay", "Raja", "Keshav", "List", "Set", "Elephant", "Drone", *Sort order:TESARDLK *Sorted Strings: "Elephant", "Set","Ajay", "Raja", "Drone","List","Keshav" """ strings=...
from random import randint number = randint(0, 100) while True: try: user_number = int(input("Enter a number: ")) except: print("that's not a number!") continue if user_number > number: print("The number is lower") if user_number < number: print("The number is higher") if user_number...
height = 4 if (height >6 ): print "Do you play basketball?" # else: # print "You probably don't play basketball..." # age = 9 # if (age < 3): # print "You're a baby!" # elif (age < 11): # print "You're probably in Elementary School." # elif (age < 13): # print ("Middle school!") # elif...
#Initializing lists: #To initiazlie an empty list: my_list = [] #To initiate a list with values (can contain mixed types): list2 = [1, "yay", 140.76] #Finding information about a list: #To get an item from a list by index: my_list= [1, 2, 3, 4, 5, 6] print my_list[0] #will give the first item in the list, which...
my_list=["hello", 123, "goodbye"] for i in my_list: print i print "" for x in range(5): print "hello" print "" for num in range(3,7): print num
import re # # patterns = ['term1','term2'] # text = "This is a string with term1, not te other!" # match = re.search('term1', text) # print(type(match.start())) # # print((match.start())) # split_term ="@" # email = "user@gmail.com" # # email.split(split_term) # print(re.split(split_term,email)) # print(re.findal...
import turtle birthday = 10187 birthday1 = 1010807 birthday2 = 20120807 Chinesse_name = '鄧凱中' English_name = 'Leo' English_name1 = 'leo' Birthday_gift = '紙片馬力歐' Birthday_gift1 = '紙片馬力歐:摺紙國王' Birthday_gift2 = 'Paper Mario' Birthday_gift3 = 'The origami king' Birthday_gift4 = 'Paper Mario: The origami king' ...
a = int(input('How many people in the whole class?')) list_score = [] name = [] nameandscore = [] for i in range(a): name_input = (input('Please enter your name:')) score = int(input('Please enter your score:')) list_score.append(score) name.append(name_input) nameandscore.append(list_score) ...
l=int(input('enter no of asterisks from left to right:')) b=int(input('enter no of asterisks from top to bottom:')) x=[] for i in range(2*l-1): x.append(' ') p=0 while p<2*l-1: x[p]='*' p=p+2 print(*x,sep="") for i in range(1,2*l-2): x[i]=' ' k=0 while k<b-2: print(*x,sep="") k=...
# Baba is rabbit # BFS 지만 시간초과로 인해 중복을 배제한 방문 배열을 정의하여 # append로 인한 시간을 줄였던게 핵심인 문제였다. import sys N = int(input()) cmd = {} for _ in range(N): p, _, q = sys.stdin.readline().split() try: cmd[p].append(q) except: cmd[p] = [q] ans = [] visited = {} Q = ['Baba'] for st in Q: try: for c in cmd[st...
#lambda functions def func(x,y,z): return x+y+z print(func(1,2,3)) myVar = lambda x,y,z:x+y+z print(myVar(1,2,3)) # List of lambdas myVar2 = [lambda x:x**2, lambda x:x**3, lambda x:x+20] for i in myVar2: print(i(2)) # Dictionary of lambdas myCalcDict = {'add': lambda x,y:x+y, ...
""" Question 1: get n-number from list(length == m and m > n), combine n-number For example: [1, 2, 3]; n =2; return [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] """ def main(list_num, n): print(list(permutation(list_num, n))) # first solution, use permutation # print(len(list(permutation(list_num, n)))) prin...
def squaresum(n): sum=0 for i in range(1, n+1): sum=sum+(i*i) return sum n=5 print(squaresum(n))
""" Example 1 """ my_list1 = [1, 2, 3, 4, 5, 6] my_list2 = my_list1 my_list1.append(7) print(my_list is 1 my_list2) print(my_list1) print(my_list2) """ Example 2 """
# importing json module import json # loading the json file and printing all the information with open('exchange_rates.json') as jsonfile: all_information = json.load(jsonfile) print(all_information) #iterate through the data and print Rates by Country def print_rates(all_information): for key, ...
string = input("Proszę wpisać dowolne słowo : ") print(string) reverse = string[::-1] print(reverse) if string == reversed: print("To jest palindrom.") else: print("To nie jest palindrom")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Este modulo gestiona el comportamiento del fuego """ from celdas import evalua_celda_vecina from main import extintores class Fuego(): def __init__(self): self.contra_incendios = False self.propagacion = 0.5 def propagacion_fuego(self, x, y,...
# This program reads from csv file and gives us the output and function is used here. import csv import sys def read_from_file(filename): with open(filename, 'r') as myfile: content = list(csv.reader(myfile)) for rows in content: print(', '.join(rows)) return filename = input('Enter ...
def indexing(blocks, squares_x): check = [] objects = squares_x ** 2 for index in range(0, len(blocks)): step = index - squares_x -1 for num in range(0, 3): count = 0 while count < 3: current = count + step if c...
import itertools import random def unit_generator(length): # Generate a list of all the combinations of the given length bp = ['A', 'T', 'G', 'C'] unit_collection = itertools.product(bp, repeat = length) unit_list = [] for unit in unit_collection: unit_list.append(''.join(list(un...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ :mod:`cercles` module :author: Sauvage Célestine ,Danneels Sophie , Soltysiak Samuel :date: November-December, 2015 Module for cercle. """ import math def create(x,y,r): """ create a circle with center x which is x-axis and y-axis and r radius :param ...
filePath = "input.txt" wordList = [] wordCount = 0 #Read lines into a list file = open(filePath, 'rU') for line in file: for word in line.split(): wordList.append(word) wordCount += 1 print wordList print "Total words = %d" % wordCount
import time print ("Module\n=================") print time.__dict__ print ("\nClass\n=================") class tClass(object): def __init__(self, x): self.x = x def double(self): self.x += self.x t = tClass(5) print t.x t.double() print t.x print t.__dict__ print tClass.__dict_...
import random function swap (list, i j): list[i], list[j] = list[j], list[i] #put the pivot in the right place and return its index function partition (list, left, right, pivot): pivot_value = list[pivot] swap (list, pivot, right) store_index = left for i in range (left, right - 1): if list[i] <= pivot_value:...
def on(text): return [word for word in text.split() if word[-2:] == 'on'] def z(text): return [word for word in text.split() if 'z' in word] def ne(text): return [word for word in text.split() if 'ne' in word] def Mai_min(text): return [word for word in text.split() if word[1:] == word.lower()[1:]]
########################### # 6.00.2x Problem Set 1: Space Cows from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ def load_cows(filename): """ Read the contents of the given file. Assumes ...
import unittest from FractionCalculator import FractionCalculator # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestCalculator(unittest.TestCase): # define multiple sets of tests as functions with names that beg...
from collections import defaultdict, Counter import re def anagram_lst(str1, str2): """verifies whether both the string are anagrams of each other""" return sorted(list(cleanString(str1))) == sorted(list(cleanString(str2))) def cleanString(str1): """a method which removes whitespaces and lowers the stri...
import unittest from HW06_Dhaval_Dongre import * class TestList(unittest.TestCase): def test_list_copy(self): """verifies whether the copy of the list is the same as the original""" self.assertEqual([1,2,3],list_copy([1,2,3])) self.assertNotEqual([1,2,2,3],list_copy([1,2,3])) def tes...
from bitset import Bitset class Valoracao(Bitset): def compare(self, valoracao): if self.getSize() != valoracao.getSize(): isEqual = False else: i = 0 while i < self.getSize() and self.test(i) == valoracao.test(i): i += 1 if i != sel...
# coding=utf-8 # 插入排序 # 插入排序的思想就是构造一个有序序列,一个无序序列 # 首先从无序序列中取出一个元素放入到有序序列中,找到合适的位置,所有大于该元素的有序元素后移,一直到无序序列为空集 def InsertSort(nums_list): for i in range(1, len(nums_list)): # i - 1 代指当前有序集合最大元素的下标 if nums_list[i] < nums_list[i-1]: temp = nums_list[i] # 哨兵记录当前无序的元素 ...
# The following iterative sequence is defined for the set of positive integers: # # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # # It can be seen that this sequence (starting at...
#coding=UTF-8 numSucessor = None numAntercessor = None numEscolhido = None print "Escolha um numero inteiro" numEscolhido = input() numSucessor = numEscolhido +1 numAntecessor = numEscolhido -1 print "O Sucessor do numero {} é {} e o antecessor do mesmo é {}.".format(numEscolhido, numSucessor, numAntecessor)
""" Author: Pranav Goel Takes user's name as input and returns a random type of house they'll have when they grow up. """ import random future = ['bungalow','mansion','villa'] name = input("What is your name?\n") num = random.random()%3 print(name,", you'll have a ",future[int(num)]," when you grow ...
''' Homework 3 @author: Carhat Eusebiu ''' import random #keep solution with its attributes class Solution: def __init__(self,sol,v,w): #solution itself self.sol=sol #value self.v=v #weight self.w=w ...
#下面的代码创建了一个餐馆类,并且创建了一个餐馆实例(对象) #每个类对应一个类对象,用以存储类的基本信息 class Restaurant(): #类对象 """一个表示餐馆的类""" #类描述 restaurant_star = 3 #类属性,直接在类中定义用类名点属性名访问 count = 0 def __init__(self, name, cuisine_type): #类的构造函数,类实例化时使用的函数 """初始化餐馆""" self.name = name.title() #实例属性,在类中self...
#!/usr/bin/python import sys import string import re def htmltowords(): print_str = "" # reading html on stdin for line in sys.stdin: # find the next <a> tag, look for href within the tag line = line.rstrip() line = string.lower(line) comp = re.split('[^a-z]', line) for c in comp: if len(c) > 3: p...
import re def name_of_email(addr): #re_noe = re.compile(r'(<(.*)>(.*)@(.*))|((.*)@(.*))') re_noe = re.compile(r'<?(\w+\s?\w+)>?.*@\w+.\w{3}') # <?和>? 表示 有一个或没有 这样就既可以匹配有<>的也可以匹配没有的 m = re_noe.match(addr) print(m.group(1)) name_of_email('<Tom Paris> tom@voyager.org') name_of_email('tom@voyager.or...
import unittest from scheduler_classes import Employee, Job, MaxHeap, schedule, remove_emp_no, remove_job_no, get_emp_no, get_job_no, \ reset_day, emp_gen class TestScheduler(unittest.TestCase): def setUp(self): self.emp_1 = Employee("john", "smith") self.emp_2 = Employee("carol", "k...
class Student: def __init__(self): print("This is non parametrized constructor") def show(self,name ): print("Hello",name ) student = Student() student.show("John") def my_function(fname): print(fname + "Ram") my_function("My Name is:")
import random import sqlite3 conn = sqlite3.connect('card.s3db') cur = conn.cursor() class CreditCard: def __init__(self): self.number = create_luhn_valid_card_number() self.pin = str(random.randint(1000, 9999)) self.balance = 0 def insert_card(card_num, crd_pin): with conn: ...
def rerun(): choice = raw_input('Enter your choice [1-4]: '); choice = int(choice); print ('***') print (' MAIN MENU ') print ('1. Back-up') print ('2. User agreement') print ('3. Reboot') print ('4. Make love to your husband') choice = raw_input('Enter your choice [1-4]: ') choice = int(choice) if choice == ...
#!/usr/bin/python import sys # The cache parameter is here for if you want to implement # a solution that is more efficient than the naive # recursive solution def eating_cookies(num_cookies, cache={}): if num_cookies in cache: # RUNTIME COMPLEXITY: O(n) ===> looping(iterating) through the cache{} object (check ...
import tweepy from flask import jsonify #handles the json dict inside the tweepy verify credientials def sendTweet(tweetMessage): api = auth() # .update_status allows us to post tweets api.update_status(tweetMessage) def sendTweetImage(tweetMessage, Image): api = auth() media = api.media_upload(Image) api.up...
#!/usr/bin/env python2 class Frame(): """frame""" def __init__(self): self.score = 0 def add(self, pins): self.score += pins class Game(): """game""" def __init__(self): self._throws = [0] * 21 self._current_throw = 0 self._first_throw = True sel...
#This program implements something I saw Yakovenko of UMD show in a presentation about inequality. #The random graph structure of the exchanges done during every tick produces a final histogram that is decidedly skewed. # The skew is motivated by the zero lower bound on individual's balances. # Set up the list of agen...
import unittest from main import add class TestMain(unittest.TestCase): #run before a functon def setUp(self): print('about to test a function') def test_add_if_variable_is_string(self): num = 'aaaå' result = add(num) self.assertIsInstance(result, ValueError) def test_add_should_return_sum(se...
#Error handling while True: try: age = int(input('what is your age?')) # print(age) # what if like this 10/age 10/age except ValueError: #can except an error type print("please enter a number") continue except ZeroDivisionError: print("please enter age higher than 0") break else...
# Strings son una secuencia de caracteres # Pueden contener a-z, 0-9, @ # entre comillas dobles o simples ( es lo mismo) a = "This is a simple string" b = 'Using single quotes' print(a) print(b) c = "Need to use 'quotes' inside a string" print(c) d = "Another wat to handle \"quotes\"" print(d) e = "This is a singl...
""" Tuple Like list but they are immutable It means you cant change them """ my_list = [1, 2, 3] print(my_list) my_list[0] = 0 print(my_list) my_tuple = (1, 2, 2, 3, 2, 3) print(my_tuple) print(my_tuple[1]) print(my_tuple[1:]) print(my_tuple.index(3)) print(my_tuple.count(2))
""" == --> Value Equality != --> Not equal to < --> Less than > --> Greater than <= --> Less than or equal to >= --> Greater than or equal to """ bool_one = 10 == 11 not_equal = 10!= 9 less_than = 10 < 100 greater_than = 10 > 10 lt_eq = 10 <= 10 gt_eq = 10 >= 10 print(bool_one) print(not_equal) print(less_than) print...
# mario in python from cs50 import get_int def main(): n = get_number() # loop for i in range(n): print(" "*(n-i-1), end="") print("#"*(i+1), end="") # print newline print() # getting height def get_number(): n = 0 while n < 1 or n > 8: n = get_int("Heig...
def reverse(input=''): i = len(input) word = '' while i > 0: word = word + input[i - 1] i = i - 1 return word
import json import os def callMenu(): choice = int(input("Enter:\n" + "<1> To register asset\n" + "<2> To view stored assets: ")) return choice def readFile(file): if os.path.exists(file): with open(file, "r") as file_json: dictionary = j...
def callMenu(): choice = int(input("Enter:\n" + "<1> To register asset\n" + "<2> To persist in file\n" + "<3> To view stored assets: ")) return choice def register(dictionary): answer = "Y" while answer == "Y": dictionary[inp...
with open("./files/page-test.html", "w") as page: page.write("<body> <h1> This is a test for the web page </h1>") page.write("<br><h2> Below are some important names for the project: </h2>") page.write("<h3>") name="" while name!="EXIT": name = input("Enter a name or EXIT: ").upper() ...
# ADD ELEMENT TO THE INVENTORY def fillInventory(list): answer = "Y" while answer == "Y": hardware = [input("\nHardware: "), float(input("Price: ")), int(input("Serial Number: ")), input("Department: ")] list.append(hardware) an...
plane={1:'Delhi to kochi at 21hr'} print 'Welcome to air ways\nHitting return will display the plae schedule' raw_input() print plane seat=['wseat','oseat'] seat1=[0,0] tseat1=0 tseat2=0 seat2=[0,0] x=0 ch='y' while(ch=='y'): if tseat1<100: print 'occupied seats are(max:50 in each):' for i in range(2): print se...
class User(): def __init__(self, id, username, password): self.id = id self.username = username self.password = password def __str__(self): return f"User ID: {self.id}" def authenticate(username, password): user = username_table.get(username, None) if user and pass...
from Aircraft.flight_algorithms import FlightBackEnd from string import ascii_letters, digits # Check for special characters from People.change_details import Change_details # User story # As an airport assistant, I want to create a flight trip with a specific destination. - John # Flight class capable of creating a...
import hashlib class CreateStaffUser: staff_name = None staff_position = None staff_username = None staff_password = None staff_password_encrypted = None def __init__(self, cursor): self.cursor = cursor def user_creation(self): # Take details on staff name self.sta...
#!/usr/bin/env python3 # coding: utf-8 import math MAJOR_AXIS = 6378137.0 # meters MINOR_AXIS = 6356752.3142 MAJOR_AXIS_POW_2 = pow(MAJOR_AXIS, 2) MINOR_AXIS_POW_2 = pow(MINOR_AXIS, 2) def deg2dms(deg): dd = deg d = int(dd) dd -= d dd *= 60 m = int(dd) dd -= m s = dd * 60 if s > 59....
''' Problem: Given an array, rotate the array to the right by k steps, where k is non-negative. Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] ''' ...
print("WELCOME TO CIPHER SOFT ") #Defining alphabets Alphabets = {} i = 1 for _ in range(97,123): Alphabets[str(chr(_))] = i i += 1 #defining functions for asking key def ask_key(): while True: try: keyin = int(input("Enter the key for coding/decoding : \t ")...
s = "Ovo je string" s[0] # označava poziciju u stringu, u ovom slučaju 0 je prva pozicija odnosno O a = str(input("Riječ: ")) print(a.upper()) # pretvara sva slova u velika tiskana print(a.lower()) # pretvara sva slova u mala tiskana "1 2 3 4 6".replace("6", "5") # zamjenjuje određeni dio stringa drugime # zamj...
def getWire(): line = input.readline().strip() return line.split(',') def getSteps(step): direction = step[0] distance = int(step[1:]) if direction =='R': return distance, 0 elif direction =='L': return -distance, 0 elif direction =='U': return 0, distance else:...
l1 = [] l2 = [] l3 = [] n = int(input("Enter number of elements: ")) for i in range(n): l3.append("a") for i in range(n): l1.insert(i, int(input("Enter order: "))) for i in range(n): l2.insert(i, input("Enter list: ")) d = dict() for i in range(n): d[l1[i]] = l2[i] for i in range(n): if (l1[i] == l...
def list2dict(lst): """ Converts a list to a dictionary """ dct = {} for w in lst: dct[w] = 1 return dct
import random import math import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import time class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z @staticmethod def add(*vectors): x = 0 y = 0 z = 0 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Assignment one Functions and Exceptions""" class ListDivideException(Exception): """class that represents and exception""" pass def listdivide(numbers, divide=2): """A function to test how many numbers are divisible by a nubmer. Args: numbers (...
# -*- coding: UTF-8 -*- import sys from correctores.common.corrector_texto import corrector_texto ######################################################################## #### Esto es lo que hay que cambiar en cada problema: #### #### - resultado: valor que debe escribir el alumno #### #...
''' class A: # this is single level Inheritance def property1(self): print("this is property 1") def property2(self): print("this is property 2") #class B inherit class A property # Class B is sub class of A class class B(A): def property3(self): print("This is ...
class MethodDemo: a=1 #cls is passed as the 1st parameter and used to access class variable @classmethod def classM(cls): print("Class method. cls.a=",cls.a) #static method: does not pass self or cls @staticmethod def staticM(): print("Static method") MethodDemo.classM() m...
#mutable courses = ['History','Math','Physics','Compsci'] course_str = ', '.join(courses) print(course_str) new_list = course_str.split(',') print(new_list) # for index,course in enumerate(courses, start=1): # print(index,course) # # print('Art' in courses)
# Arithmetic Operators: # Additions # Division 3/2 # Floor Division 3//2 # Exponent 3**2 # Modulus 3%2 num_1='100' num_2='200' num_1=int(num_1) num_2=int(num_2) print(num_1+num_2)
#9-1-2019 #Program untuk mengetahui jenis error # angka = 91 # # try: # print(angka / 0) # except Exception as err: # print("Maaf proses perhitungan gagal karena: ", err) # except ValueError as err: # print("Proses perhitungan gagal karena: ", err) # try: # angka_pertama = int(input("Masukkan nilai an...
# def permainan(): # print("\nHalo ", nama) # kamu = int(input("Masukan pilihanmu: ")) # kom = random.choice(["Batu", "Gunting", "Kertas"]) # if kamu == 1: # print("Kamu : Batu") # print("Komputer :", kom) # if kom == "Batu": # print("\tDraw, ",nama) # if...
data = [int(s) for s in input("Masukan data: ").split()] # .........0.......1.........2...... nilai = ["Ayam", "Sapi", "Kambing", True, 0.9, 2] print(nilai) # print(data2) # data.sort() print(data) # menampilkan data dengan perulangan for for data in nilai: print("Nama-nama heiwan : ", data) # for data in range...
print(''' Daftar Buah : 1. Mangga 2. Jeruk 3. Durian ''') buah = int(input('Pilih buah : ')) jumlah = int(input('Berapa banyak : ')) harga = {"Mangga": 15000, "Jeruk": 12000, "Durian" : 50000} def mangga(jumlah, buah): hitungan = jumlah * buah return hitungan print(mangga(buah,jumlah)) # ...
# 25-02-2019 for jumlah in [1, 2, 3, 4, 5]: print(jumlah) print("Selesai", jumlah, "patra") nama1 = "Rio" nama2 = "Gani" print(nama1 + nama2) print(100*"=") # menggunakan persen s # print("Hello" %s, "Hello") # memanggil list my_array = [1, 2, 3, 4, 5] print(my_array[4]) print("+"*100) # mengaksek array den...
class Printer: # variabel global q_list = [] front = 0 rear = 0 n_items = 0 max_size = 0 def __init__(self, x): self.max_size = x self.q_list = [0] * self.max_size self.front = 0 self.rear = -1 self.n_items = 0 # menambahkan data (data pertama ak...
# 4 - 12 - 2018 Selasa nilai_awal = int(input("Masukan bilangan awal: ")) nilai_akhir = int(input("Masukanan bilangan akhir: ")) cacah = int(input("Masukan bilangan cacah: ")) for ulang in range (nilai_awal, nilai_akhir, cacah): # print("Nilai awal adalah: ", nilai_awal, "dan Nilai akhir adalah: ", nilai_akhir) ...
g = [[1, 2, 3], [4, 5, 6]] for indeks_baris in range(0, len(g)): for indeks_kolom in range(0, len(g[indeks_baris])): print(g[indeks_baris][indeks_kolom], end=" ") print() # looping adalah pembacaan pola # harus mengetahui polanya agar outpunya sesuai dengan keinginan
class Queue: # variabel global q_list = [] front = 0 rear = 0 n_items = 0 max_size = 0 def __init__(self, x): self.max_size = x self.q_list = [0] * self.max_size self.front = 0 self.rear = -1 self.n_items = 0 # menambahkan data (data pertama akan...
# 4-12-2018 Selasa #contoh while dengan break # count = 0 # while True: # print(count) # count += 1 # if count >= 5: # break #contoh for dengan continue # for x in range (10): # #check if x is even # if x % 2 == 0: # continue # print(x, end=" ") # # print("="*100, end=" ") # # ...
print("Program untuk menghitung upah") #input jam_kerja = float(input("Masukan jumlah jam kerja Anda dalam satu minggu : ")) bayaran = float(input("Masukan Bayaran anda per-jam : ")) if jam_kerja <= 48: gaji = jam_kerja * bayaran elif jam_kerja > 48: x = jam_kerja - 48 bonus = bayaran + 2000 gaji = 4...
""" Created on Thu Mar 05 2020 @author Giovanni Gabbolini """ import re def preprocess_uri_name(name): """given a name of an entity, it returns the name of that entity as it would be formatted as it was a name in dbpedia by formatted we mean that: - every letter of words separated by a space or a dash are...
from collections import Counter from hacker.decoder import decode value = 'SOGsQPkdgykeOUfBnJfykKttIeQkxIKVXnGykxnGisnePdCVuKxkIxkVnIClKwXlOnQOsJyRuVKtnuKxktcIeQKCkJsQCIfUkMgkLyggvUktXftKkQPKNgIQknnLsVdgktsJVLIcoDgtnXkljCdOCkJCmnJkCJIyLudJgVkdOtkOJiiJkWggQkcWiIeQkfBIXKocnhCNknfIKewsCKbkeOVkLnVIJSfunFSIQksQkCdgJktXQfC...
from typing import Callable, List from hacker.hackvm.integers import verify_integer class OperandStack: """ Operand stack for the hack vm that allows the operations specified for that. Though it is called a stack, it allows for several non-stack operations (accessing elements other than the last push...
from datetime import datetime from decimal import Decimal from typing import Any, Callable, Container, Iterable, Optional, Type, TypeVar, Union # We define predicates as functions that return a boolean: Callable[[Any,...], bool]. # This file contains (functions that return) predicates intended for use with the pre/pos...
def _is_pandigital_product(multiplicand: int, multiplier: int) -> bool: product = multiplicand * multiplier return sorted(f'{multiplicand}{multiplier}{product}') == ['1', '2', '3', '4', '5', '6', '7', '8', '9'] def problem_0032() -> int: # The ranges are set based on reasoning based on the amount of digi...
def x_max(iterable, amount=1, key=None): """ Returns the largest items in the input :param iterable: An iterable :param amount: The amount of results :param key: The key with which to compare items :return: An iterable containing the 'amount' largest items in the 'iterable' """ return s...
from abc import ABC, abstractmethod from typing import List, Dict, Callable class Operation(ABC): @abstractmethod def execute(self, computer: 'IntcodeComputer', parameter_modes: str): ... class ReadReadWriteOperation(Operation, ABC): def execute(self, computer: 'IntcodeComputer', parameter_modes...
from math import gcd from projecteuler.util.enumeration import digit_range def _is_digit_cancelling_fraction(numerator: int, denominator: int) -> bool: """ Returns whether the passed fraction is equal to the fraction made up of the first digit of the numerator and the second digit of the denominator ...
from __future__ import annotations from enum import IntEnum, unique from random import randint from typing import Tuple @unique class DieType(IntEnum): """ a type of die used in the Pathfinder system """ D1 = 1 D2 = 2 D3 = 3 D4 = 4 D6 = 6 D8 = 8 D10 = 10 D12 = 12 D20 = 20 ...
# Written by Lei Wu and Simon Williams with code snippets from a variety of sources import numpy as np import pandas as pd import pygplates import matplotlib.pyplot as plt import math import pmagpy.pmag as pmag def distance_on_unit_sphere(lat1, long1, lat2, long2): # Convert latitude and longitude to # spher...
import random a = str(input("")) b = random.randint(0,2) # 0 is Rock # 1 is Paper # 2 is Scissor if a == "Rock" and b == 0: print("You picked: Rock") print("Computer picked: Rock") print("It's a draw!") elif a == "Rock" and b == 1: print("You picked: Rock") print("Computer picked: Paper"...
try: score = float(input("Enter a score between 0.0 and 1.0\n")) if score < 0.0 or score > 1.0: print("Out of range") elif score >= 0.9: print("A") elif score >= 0.8: print("B") elif score >= 0.7: print("C") elif score >= 0.6: print("D") else: print("F") except: print("Bad score input")