text
stringlengths
37
1.41M
# JULY 17, 2019 # The following program is a solution to Cracking The Coding Interview: Question 4.1 # Route Between Two Nodes : Given a directed graph, design an algorithm to find out # whether there is a route between two nodes. # First we define an arbitrary graph using a python dictionary data structure. ...
# -*- coding: utf-8 -*- """ @author: Alejandro Moya García """ import random class Selection: """ Performs a parent selection using tournament algorithm """ def tournamentSelection(population, numParents, tournamentSize): matingPool = [] populationCopy = population.cop...
class Stack(object): def __init__(self, size=50): self.items = [] self.length = 0 self.size = size def __str__(self): print(self.items) return '' def push(self, value): if len(self.items) > self.size: raise StackOverflowError self.items....
class ListNode: def __init__(self, data): "constructor to initiate this object" # store data self.data = data # store reference (next item) self.next = None return def getData(self): "method to return the value of the node" return self.data ...
#!/usr/bin/python def displayPathtoPrincess(n, grid): src_col = -1 src_row = -1 dest_col = -1 dest_row = -1 for row, line in enumerate(grid): if src_col == -1: src_col = line.find('m') src_row = row if dest_col == -1: dest_col = line...
# Implement a class to hold room information. This should have name and # description attributes. class Room: # def __init__(self, name, description, n_to, s_to, e_to, w_to): def __init__(self, name, description): self.name = name self.description = description self.items = [] # self.n_to = None ...
from pymongo import MongoClient import pymongo import csv import urllib.request import pprint import json client = MongoClient('localhost', 27017) db = client.test posts = db.posts # running retrieve_all_information() will give you a dictionary # key: project ID (numbered 1 through however many projects) DEPRECATED ...
import requests as rt var=True while var: city=raw_input("enter the city name : ") url="http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=APIKEY" data=rt.get(url) read=data.json() print "Cityname : {} ".format(read['name']) print "Temperature : {} ".format(read['main']...
import math # return manhattan distance between two coordinates def manhattan(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) # return cell position given coordinates def position(coordinates, cell_width): x, y = coordinates return (math.ceil(x / cell_width) - 1, math.ceil(y / cell_width) - 1) # retur...
n1 = float(input("Ingresa el primer número: ")) n2 = float(input("Ingresa el segundo número: ")) def suma(val1=0, val2=0): return val1 + val2 def resta(val1=0, val2=0): return val1 - val2 def multi(val1=0, val2=0): return val * val2 def operacion(funcion, val1=0, val2=0): return funcion(val1, val2) ...
def merge(dict1, dict2): """ Merge two dictionaries. :param dict1: :param dict2: :return: """ for k in dict2: if k in dict1 and isinstance(dict1[k], dict) and isinstance(dict2[k], dict): merge(dict1[k], dict2[k]) else: dict1[k] = dict2[k]
import os import requests from datetime import datetime class WorldTimeAPI: DEFAULT_DOMAIN = 'http://worldtimeapi.org' def __init__(self): self.base_domain = os.getenv('TIME_API') or self.DEFAULT_DOMAIN def get_time_at_timezone(self, tz): """ tz should be a valid timezone of the ...
a = [38, 21, 53, 62, 19] smallest = a[0] for i in a: if i < smallest: smallest = i print(smallest) a = [38, 21, 53, 62, 19] biggest = a[0] for i in a: if i > biggest: biggest = i print(biggest) a = [i for i in range(0, 11)] b = list(i for i in range(0, 11)) a = ['alpha', 'bravo', 'charlie', ...
# Hello, World! 출력 print('Hello, world!') print("Hello, world!") print('12345X7890') """ 여러줄 주석 """ print("hello") ''' 여러줄 주석 ''' print("hello") # 수학 = 기호는 같다, 프로그램에서는 = 대입연산자 # 좌변 = 우변 : 우선순위 때문에 우변의 값, 변수, 수식이 먼저 연산 후 좌변(변수만) 대입됨 ex) a = 1 + 2 # 프로그램에서 같다는 어떻게 표현할까요? == 동등 연산자 a = 1 + 2 if a == 10: # 파이썬에서는 ...
password = '20sk' print(password) if len(password) < 5: print('5자 이상 입력하세요.') else: print('정상 처리되었습니다') hello = '안녕하세요' length = len(hello) print(len(hello.encode('utf-8'))) hello = 'Hello, ' world = 'world!' print(hello + world) print(hello * 2) hello = 'hello ' print(hello * 0) print(hello * 3.5) prin...
""" chicken caesor salad """ import string alpha_down = string.ascii_lowercase alpha_up = string.ascii_uppercase cipher_text = "qkbn{ePmv_lQL_kIMamZ_kQxpMZa_oMb_aW_pIZl}" global plain_text, alpha_location plain_text = "" alpha_location = 0 print(f"Cipher text = {cipher_text}\n") #find the shift value one = "i" two =...
import sys p = True num = int(sys.argv[1]) for item in range(2,num-1): print(item) if (num%item) == 0: p = False # print ("num is not a prime") break else: continue if (p == True): print (" num is prime") else: print(" num is not a prime")
from math import log from sys import stdin from sys import stdout import my_queue class TreeNode: def __init__(self, key, value, parent=None): self.key = key self.value = value self.left = None self.right = None self.parent = parent def get_parent_key(self): r...
import urllib ''' 掌握对参数进行编码 使用parse.urlencode ''' from urllib import request,parse if __name__=="__main__": url='http://www.baidu.com/s?' wd=input('input your keyword') qs={"wd":wd} qs=parse.urlencode(qs) full_url=url+qs print(full_url) rsp=urllib.request.urlopen(full_url) ...
"""An example of how to represent a group of acquaintances in Python.""" # Your code to go here... import json import statistics group = { "Jill": { "age": 26, "job": "biologist", "relations": { "Zalika": "friend", "John": "partner" } }, "Zalika": {...
from lecture1 import calculator as funcs # from calculator import sum,divide class Calculator: def __init__(self): pass @staticmethod def sum(m, n): return funcs.sum(m, n) @staticmethod def div(m, n): return funcs.divide(m, n) aCalculator = Calculator() print(aCalculat...
from tkinter import * class Matchinggame: def __init__(self): self.__window = Tk() self.__window.title("Unit changer") self.__from_unit = "unit1" self.__to_unit = "unit1" self.__FromLabel = Label(self.__window, text="From") self.__FromLabel.grid(ro...
import datetime import tkinter as tk from dateutil.relativedelta import relativedelta class Person: def __init__(self, name, birthdate): self.name = name self.birthdate = birthdate def __str__(self): return "Name: {}, Birthdate: {}".format(self.name, self.birthdate) def age(self)...
a = b = c = 1 a, b, c = 1, 2, "john" #Numbers var1 = 1 var2 = 2 del var1, var2 mystr = 'Hello world' print mystr # Prints complete string print mystr[0] # Prints first character of string print mystr[2:5] # Prints characters starting from 3rd to 5th print mystr[2:] # Prints character...
#Dictionary dict1 = {'Name': 'Zara', 'Age': 7} print "dict['Name']: ", dict1['Name'] print "dict['Age']: ", dict1['Age'] #Updating dict1['Age'] = 8; # update existing entry dict1['School'] = "DPS School"; # Add new entry print "After update", dict1 #Dictionary functions cmp(dict1, dict2) #comparing len(dict1) # le...
"""Implementation of the Ordered Neuron LSTM Layer based in keras LSTM Layer.""" import tensorflow as tf from tensorflow.python.keras import activations from tensorflow.python.keras import backend as K from tensorflow.python.keras import initializers from tensorflow.python.keras import regularizers from tensorflow.pyth...
jasi = int(input("Jansin'di kirit: ")) if jasi <= 6: print("Sizge kiriw beypul") elif jasi <=18: print("Sizge kiriw 15 ming sum") else: print("Sizge kiriw 25 ming sum")
from tkinter import * tk = Tk() while True: tk.configure(background="light blue") tk.maxsize(900,700) tk.minsize(900,700) tk.title("Fuel System") tk.wm_iconbitmap('fuel.ico') title = Label(text="Fuel", font=("Courier", 40), bg="light blue") def cal(): if str(aznbox.get()) == "": ...
def user_menu(): print("Welcome to the Historical Quotes Quiz") print("1. Start the quiz") print("2. Exit the game") option = input("Please select your option > ") print("\n") return option def quiz_game(): score = 0 question_1 = input("Don't cry because it's over, smile because it happ...
#!/usr/bin/python3 #-*-coding=utf8-*- from functools import reduce import math #Map def f(x): return x*x L = [1,2,3,4,5] res = map(f,L) print(list(res)) #Reduce def add(x,y): return x + y data = reduce(add, L) print(data) #Str into int def fn(x,y): return x *10 + y def char2num(s): digits = {...
#!/usr/bin/python name = ['aaa', 'bbb', 'ccc'] age = [1,2,3] zip_res = zip(name,age) print "zip result is:",zip_res for name,age in zip_res: print "%s's old is %d" % (name,age)
#!/usr/bin/python class SchoolMember: def __init__(self, name, age): self.name = name self.age = age print '(Initialized SchoolMember: %s)' % self.name def tell(self): print 'Name:%s, Age:%d' % (self.name, self.age), class Teacher (SchoolMember): def __init__(self, name, age, ...
# -*- coding: utf-8 -*- #request练习 #用request爬去纵横网小说排行前三页 import requests def OpenUrl(url): req = requests.get(url) return req.text def SaveHtml(html,filename): with open(filename,'w',encoding='utf-8') as f: f.write(html) def Main(): for i in range(3): base_url = 'http://www.zongheng.com/...
from celestial_object import Cel_object from planet import Planet from sun import Sun from satellite import Satellite from route import Route from vector import Vector from read_planets import Read_planets class Solar_system: ''' Initializes a Solar_system type ''' def __init__(self): self._satellites = [] # l...
# import os # # 주어진 디렉토리에 있는 항목들의 이름을 담고 있는 리스트를 반환합니다. # # 리스트는 임의의 순서대로 나열됩니다. # file_path = 'C:\\Users\\jeong\\Desktop\\사진\\pictures' # file_names = os.listdir(file_path) # i = k_item +1 # for name in file_names: # src = os.path.join(file_path, name) # dst = str(i) + '.jpg' # dst = os.pa...
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder, their colleagues and Cory Reck. """ ######################################################################## # DONE: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. ####...
# Cynthia Cho # DSC 430 # Due: January 22, 2019 # I have not given or received any unauthorized assistance on this assignment. ### Problem 1 ### def rec_1(a): """calculates the upper right hand corner coorindates of 1st rectangle""" rec1=[] for i in a: res=i +a[2] ...
""" Delete a File""" import os os.remove('demofile.txt') """ Check if File exist:""" if os.path.exists('demofile2.txt'): os.remove('demofile2.txt') else: print("File Not Existed") """ Delete Folder """ os.rmdir('myfolder')
""" syntax::-- output_list = [output_exp for var in input_list if (var satisfies this condition)] """ """ Example 1""" input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] list_using_comp = [var for var in input_list if var % 2 == 0] print("Output List using list comprehensions:", list_using_comp) """ Example 2""" list_usin...
""" 1.append 2.clear 3.copy 4.count 5.extend 6.index 7.insert 8.pop 9.remove 10.reverse 11.sort """ a = [1, 2, 3] b = [4, 5, 6] c = [1, 2, 3] """1.append""" a.append(1) print(a) a.append([1, 2, 3]) print(a) """2.clear""" a.clear() print(a) a *= 0 print(a) del a[:] print(a) """3.copy""" d = c.copy() print(d) # shal...
import random play_again = True while play_again: answer = random.randint(1, 3) answer_arr = [' ', ' ', ' '] answer_arr[answer - 1] = '*' print("Can you find the star (Choose one of the numbers)?:\n") choice = int(input("[ 1 ]--[ 2 ]--[ 3 ]\n")) print(f"[ {answer_arr[0]} ]--[ {answer_arr[1]} ]...
person = { "name": "Keenan", "age": 22, "hometown": "Omaha, NE" } print(f''' Hi, my name is {person.get("name")}. I am {person.get("age")} years old and I come from {person.get("hometown")}. ''')
#流程控制 """ if condition_1: statement_block_1 elif condition_2: statement_block_2 else: statement_block_3 """ var1 = 20 if var1: print("var1:",var1) var2 = False if var2: print("var2:",var2) print("end") print("==========================================="); # var3 = 10 # if var3<10: # print(...
from cs50 import get_int def left_triangle(h, i): for j in range(1, h + 1): if (j < i): print(' ', end='') else: print("#", end='') def right_triangle(h, i): for j in range(1, h + 1): if (j <= i): print("#", end='') def get_positive_int(prompt): ...
#!/usr/bin/python # -*- coding: latin-1 -*- from __future__ import print_function import re import nltk import datetime from time import strptime class Tokenize: """ Splits news story into sentences and words. """ def __init__(self,paragraph): self.paragraph = paragraph def split_story(...
# This is a Python program to print all positive numbers in a range (Task2) numList = [] Number = int(input("Please enter the Total number of list Elements: ")) for i in range(1,Number + 1): value = int(input("Please enter the value of %d Element : " %i)) numList.append(value) print("\nPositive Number...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Apr 21 15:21:30 2018 @author: soojunghong """ #-------------------- # import libraries #------------------- import csv import os import pandas as pd #------------------ # functions #------------------ def csv_reader(file_obj): reader = csv.reade...
def decode_string(s): # decode string by specified encoding rule # ("4[ab]") => "abababab" # l=2,r=4 # ("2[ab3[c]]") => "abcccabccc" # ("") => "" left_index = 0 right_index = 0 pre_chars = '' for i in range(len(s)): if s[i].isalpha(): pre_chars += s[i] elif s[i] == '[': left_index = i break; ri...
def navigator(alterFunction): with open("../input05.txt") as fp: nums = list(map(int, fp.readlines())) print(len(nums)) i = 0 c = 0 while 0 <= i < len(nums): c += 1 j = i + nums[i] nums[i] = alterFunction(nums[i]) i = j print(c,i,j) def p9(num): return num + 1 def p10(num): if num<3: ...
from math import floor def fuel_rocket_calc(): f = open('../input/input_dia1.txt') fuel_by_module = [] for mass in f: fuel = calc_fuel(mass) fuel_by_module.append(fuel) return fuel_by_module def fuel4fuelmass(rocket_fuel): sum_fuel = 0 for fuel in rocket_fuel: new_fuel...
n = int(input("choose a number? ")) acc = 1 for i in range(1, n+1, 1): acc = acc * i print(acc)
import tensorflow as tf kInputPadding = 6 kScaleFactor = 4 kOutputPatchSize = 64 kInputPatchSize = kOutputPatchSize + 2 * kInputPadding def getModel(): model = tf.keras.Sequential() inputShape = (kInputPatchSize, kInputPatchSize, 3) print("Input shape: " + str(inputShape)) # See section 6 here: #...
# Basic mathematical operations in Python # Get user Input a = input("fist number:") b = input("second number:") # sum of 2 numbers sum = int(a) + int(b) # subtract two numbers diff = int(a) - int(b) # Multiply two numbers mul = float(a)*float(b) # Divide two numbers div1 = float(a)/float(b) # Divide two numbers such...
import os import binascii import hashlib def get_salt(): """ Returns a hex-encoded cryptographically secure random salt string. :return: Hex encoded string. """ salt = os.urandom(16) return binascii.hexlify(salt).upper() def hash_pass(salt, secret): """ Given a salt and a secret, returns a hex-encode...
#Data Preprocessing - Part 1 #Importing Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values #Encoding Categorical variables from sklearn.prep...
class PhonePlan: # FIXME add constructor ''' Your solution goes here ''' def __init__(self, num_mins = 0, num_messages = 0): self.num_mins = num_mins self.num_messages = num_messages def print_plan(self): print('Mins:', self.num_mins, end=' ') print('Messages:', self.nu...
import sys from spellchecker import spellchecker def get_file(): print("Welcome to Text File Spellchecker") flag = False # check file name is valid file fileName = input("Enter the name of the file to read: ") while(flag == False): try: file = open(fileName, "r") print...
from room import Room from maze import Maze ''' This maze has three rooms. The player walks north from the start room gets to a middle room. The middle room leads to the exit. ''' my_rooms = [] my_rooms.append(Room("You are in room 1.")) my_rooms.append(Room("You are in room 2.")) my_rooms.append(Room("You are i...
class Node(): def __init__(self, data): self.__value = data self.__left = None self.__right = None def getLeft(self): return self.__left def getRight(self): return self.__right def getValue(self): return self.__value def setLeft(self, l): ...
''' Full name: Quang Bui Drexel user ID: 14392331 Purpose of the file: The Text class inherits from Drawable and it will be used to display the player’s score. Text class will implement the draw() and get_rect() method in order to create some Text. ''' import pygame from drawable import Drawable ...
import random def monster(): mon = [] print("你遇到某單位處長") print("以下是處長的數值") mon_Atk=random.randint(410,500) print("西瓜數量",mon_Atk) mon_Def=random.randint(300,400) print("防護衣",mon_Def) mon_Hp=random.randint(700,800) print("精神指數",mon_Hp) print() mon.append(mon_Atk) mon.append(mon_Def) mon.append(mon_Hp) return...
class Movement: """No movement""" moves = [] attacks = [] class HorseMovement(Movement): """Regular horse/king movement: can move once in L.""" moves = [(2, 1), (2, -1), (1, -2), (1, 2), (-1, 2), (-1, -2), (-2, 1), (-2, -1)] attacks = [(2, 1), (2, -1), (1, -2), (1, 2), (-1, 2), (-1, -2), (-2, ...
from funtions import * numeros = [] nro=int(input("Números: ")) while nro!=0: numeros.append(nro) nro=int(input("Números: ")) eliminar=int(input("Número a eliminar: ")) if eliminar in numeros: numeros.remove(eliminar) else: print("Ese número no está entre los ingresados.") print("Sumatoria d...
number=int(input("Enter a number:")) if number<0: number*=-1 #number=number*-1 print("The absolute value is", number)
def list_nr(list): return all([x >= 0 and x == int(x) for x in list]) def list_list(list): return any([x[0] == x[-1] for x in list]) def mat(list): return all([all([x==0] for x in [y for y in list])]) def sir_in_lista(sir, list): return any([x in sir for x in list]) print(lis...
def multimi(list): return set([x for x in list if str(x)[0] == str(x)[-1]]) def diagonal(list): return sum([list[i][i] for i in range(0,len(list))]) #print(multimi([1, 2, 100, 101, 101])) print(diagonal([[1, 2], [3, 4]]))
import json def get_numbers(data, numbers): try: for k, v in data.items(): if type(v) == dict or type(v) == list: get_numbers(v, numbers) elif type(v) == int: numbers.append(v) except AttributeError: for v in data: if type(v) ...
class TrainerStats: """ Trainer stats class """ def __init__(self, num_trainers, num_gym_leader, num_regular_trainer, num_have_partner, num_per_location): """ Constructor for TrainerStats """ self._num_trainers = num_trainers self._num_gym_leaders = num_gym_leader ...
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm # ----------------- Generate Data ------------------------ # def gen_data_non_linear(N,D,sigma): """ Inputs N - integer number of data points D - number of dimensions sigma - noise Return X,Y,Y_true""" X = np.ran...
class Team: """ Represents a team """ def __init__(self, name, app): """ Initialize the team """ self.name = name self.points = 0 self.app = app def score(self): """ Score a goal for this team """ self.points += 1 if self.po...
from multiprocessing import Process, Queue from threading import Thread import time def producer(q): for i in range(10): res = "包子%s" % i time.sleep(0.3) print("生产者生产了%s" % res) q.put(res) def consumer(q): while True: res = q.get() time.sleep(0.5) prin...
from tkinter import Label, Button, Tk, Text, Scrollbar import self as self root = Tk() class MainGui: def __init__(self, nickname): root.title("ChatBox v1. Client: {}".format(nickname)) root.geometry("340x450") Message() Btn('Отправить', 'send_msg') MessageLabel() ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Author cpp @Date 2021/10/28 18:45 @Describe @Version 1.0 """ def serveTriangle(a, b, c): flag = 0 if a + b <= c and a + c <= b and b + c <= a: print("不能构成三角形") elif a == b == c: print("构成等边三角形") elif a == b or a == c...
# -*- coding: utf-8 -*- #define a binary search tree class #The BinarySearchTree class has a reference to the TreeNode that is the root of the binary search tree. #binary search tree class create the real tree #why iterator:这样做有什么用呢?试想想在迭代指针还没指到的当前元素时候,已经迭代之后的位置元素,那些元素需要计算么? #因为只有迭代到当前位置的元素时候,才开始计算元素的值。在迭代之前可以不存在,在迭代之后...
'''Binary Search Trees Binary tree: Tree where each node has up to two leaves 1 / \ 2 3 Binary search tree: Used for searching. A binary tree where the left child contains only nodes with values less than the parent node, and where the right child only contains nodes with values greater than or equal to t...
name = "Carnegie" videogame = "madden 18" tvshow = "The Flash" city = "New York" class = "Math" print ("Hello " + name) print ("Have you played " + videogame + "recently?") print("What's your favorite class?") subject = input(Math) if subject == "Math": print("Nice!") else: print(subject + " I...
##self define Exception class myException(Exception): pass ##throw an Exception def division(x,y): if y == 0: raise ZeroDivisionError('not allow for dividing 0') return x/y try: division(1,0) except ZeroDivisionError as e: print (e) except (ZeroDivisionError,ValueError) as e: prin...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: max_sum = -(1 << 31) def maxPathSum(self, root): """ :type root: TreeNode :rtype: int ...
def main(): outputString = "" inputString = "(S (NP (NNP James)) (VP (VBZ is) (NP (NP (DT a) (NN boy)) (VP (VBG eating) (NP (NNS sausages))))))" inputString = inputString.strip().split(' ') print (inputString) for word in inputString: if word.endswith(')'): outputString = output...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # newhead = None # ...
import random #We will choose the values of p and q for a list composed from prime numbers(from 2 to 50) def prime(n): if n <= 1 : return False if n == 2: return True for i in range(2, n): if n % i == 0: return False else: return True l...
""" Lista de dez números """ numeros = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] """ Imprimindo individualmente """ print (numeros[0]) print (numeros[1]) print (numeros[2]) print (numeros[3]) print (numeros[4]) print (numeros[5]) print (numeros[6]) print (numeros[7]) print (numeros[8]) print (numeros[9]) """ Utili...
# import sys # # if len(sys.argv) != 2: # raise ValueError('Please provide email-id to send the email.') # print(f'Script Name is {sys.argv[0]}') # email = sys.argv[1] # print(f'Sending test email to {email}') # import getopt # import sys # argv = sys.argv[1:] # opts, args = getopt.getopt(argv, 'x:y:') # # list of...
# number: int, float, complex num_int = 124789 num_float = 6.12 # A floating point number is accurate up to 15 decimal places. num_complex = 7 + 3j print(num_int, num_float, num_complex) print(type(num_int), type(num_float), type(num_complex)) print(isinstance(num_int, int), isinstance(num_float, float), isinstance(n...
import pygame, sys, random pygame.init() while True : a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 g = 7 h = 8 i = 9 j = 10 you = raw_input("Choose a Number: ") if you == "1": print 1 answer = 1 if you == "2": print 2 a...
"""User model tests.""" # run these tests like: # # python -m unittest test_user_model.py from unittest import TestCase from sqlalchemy.exc import IntegrityError from models import db, User, SavedSearch from app import app app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///restroom-finder-test' db.create...
# Emerson Efficiency Plan nrph = float(input('Normal rate / hour : ')) sopw = float(input('Standard ouput / week (unit) : ')) stpu = float(input('Standard time / unit (hour) : ')) worker = int(input('Quantity of worker/s : ')) rphg = nrph * stpu * sopw # Rate / hour guaranteed for each in range(worker) : print(f'\...
# perfect Number questioning while True: number = int(input("Give me a number: ")) divisors = list() for f in range(1, number): if number % f == 0: divisors.append(f) sums = 0 for fck in divisors: sums += fck if sums == number: print("...
# parameters In Functions # we dont have to give parameters to a function everytime. # Look at that: def hello(nick): print("hello", nick) #if we want to use that Function, we have to give a parameter. #like that: hello("nihil") hello("okan") # if we don't want to give a parameter when we're usin...
# Exercise - 1: # Get user's weight and height values, calculate body index and if: # BKİ 18.5'un altındaysa -------> Weak # Index 18.5 between 25 ------> Normal # Index 25 between 30 arasındaysa --------> overweight # Index above 30 ------------> Obese # Index calculate: Weight / Height(m) * Height(m...
# for Loops myList = [1,2,3,4,5,6,7,8,9] total = 0 for f in myList: total += f print("{} is added to total.\nAnd total is {} now!".format(f, total),end = "\n\n") print(". . .", end = "\n\n") print("Loop is ended. And total result is:",total) # Print even numbers. myList2 = [1,2,3,4,5,6,7,8,9]...
#Given a string, find the length of the longest substring without repeating characters. #Input: "pwwkew" #Output: 3 #Explanation: The answer is "wke", with the length of 3. # Note that the answer must be a substring, "pwke" is a subsequence and not a substring. class Solution(object): def lengthOfLo...
#Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. class Solution: def validPalindrome(self, s): first = 0 last = len(s) - 1 deleted = 0 while first <= last: if s[first] == s[last]: first = first + 1 last = last - 1 else: if first < ...
import unittest class lifo_n: def __init__(self, n=10): self.array = [None] * n self.index = 0 self.size = n def push(self, item): if self.index < self.size: self.array[self.index] = item self.index += 1 else: print "stack full" ...
from collections import MutableSequence, namedtuple class LinkedList(MutableSequence): class Node(object): __slots__ = ("value", "prev", "next") def __init__(self, value, prev, next): self.value, self.prev, self.next = value, prev, next def __init__(self, seq): self._head ...
import pandas as pd data = [] # Voor het berekenen van de gemiddelde artikel lengte aLen = [] # Voor het berekenen van de gemiddelde sammenvatting lengte sLen = [] def getData(subject, amount): global data global aLen global sLen for i in range(amount): dataItem = [] dataItem...
# assignment 1 import re with open('baby2008.html', 'r') as f: contents = f.read() pattern = re.compile(r'Baby Names') matches = pattern.finditer(contents) for i in matches: print(i) # assignment 2 with open('names.txt', 'r') as p: content = p.read() print(content) #as...
class Node: def __init__(self, key): self.key = key self.left = None self.right = None class BTree: def __init__(self): self.root = Node(15) def newNode(self, key, node): if node.left == None: node.left = Node(key) elif node.right =...
""" Input Output dalam Bahasa Python Date : Saturday, 7/12/2019 Author : Pasyah Vegananda GitHub : PVegananda """ print("Output Print") #Output menggunakan print #Hasil """ Output Print """ var_1 = 5 #Membuat Variabel var_1 print("The Value is", var_1) #Memberikan Outpu...
# -*- coding: utf-8 -*- """ Created on Wed Apr 29 09:34:55 2020 @author: sakshi """ # starting from the 1st character every "n" characters from a string str3 = "python ia a programming language. i am learning python and is very easy. python is based on oops. python is also a type osf snake" str3[::3] # i...