text
stringlengths
37
1.41M
import pandas as pd import numpy as np import os from pprint import pprint from sklearn.cluster import KMeans import csv """ Reads the data from CSV files, each attribute column can be obtained via its name :param filePath: the file path of the input data frame :type filePath: str :returns: return the dataframe aft...
import pandas as pd import numpy as np import sys import os from pprint import pprint from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import csv """ Reads the data from CSV files, each attribute column can be obtained via its name :param filePath: the file path of the input data...
# from PyPDF2 import PdfFileWriter,PdfFileReader # pdf1=PdfFileReader(open("readme.pdf")) # pdf2=PdfFileReader(open("readme.pdf")) # writer = PdfFileWriter() # # add the page to itself # for i in range(0,pdf1.getNumPages()): # writer.addPage(pdf1.getPage(i)) # # write to file # with file("destination.pdf", "wb"...
#Russian Peasants Algo def Peasants (a,b): x = a; y = b z = 0 while x > 0: #This timesing algorythm works by selecting if x is even, halving that, then doubling y. If x is odd, the value of y is added to z, y is doubled for the next iteration. if x % 2 = 1: z = z + y y = y << 1 ...
#Please remember to play here: http://www.codeskulptor.org/ - the simplegui library is not standard. # implementation of card game - Memory import simplegui import random HEIGHT = 100 WIDTH = 800 # helper function to initialize globals def new_game(): global state, exposed, state, cards, card1, card2, moves ...
import urllib website = raw_input("Enter website: ") html = urllib.urlopen(website).read() valid = urllib.urlopen(website).getcode() print valid if valid != 200: print "This is not a valid page." else: print html[:3000] count = len(html) print count
import operator class HighScoreManager: """ Class for handling a list of Highscore instances """ def __init__(self, data, poker=False): self.heading = data.pop(0) self.highscore_list = self.create_list(data) self.poker = poker def create_list(self, data): """ ...
##Muataz Badr ## mmb244@usask.ca import re ## It seems like it was not necessary to create Multiple versions of the code as the REGEX call covers multiple aspects ## of the different questions asked and covers the bonus questions as well. ## odler versions are found at the end of the file.(EDITED) # VERSION 2 , BO...
import sqlite3 import json import math class Pothole(object): def __init__(self, creation_date, status, completion_date, response_time,\ service_num, current_activity, action, potholexblock, \ street, zip_num, ward, lat, lon, urgency_level, \ traffic_count, stre...
import sqlite3 sl_conn = sqlite3.connect('demo_data.sqlite3') sl_cur = sl_conn.cursor() # Creating table demo table = """ CREATE TABLE demo( s VARCHAR (10), x INT, y INT ); """ sl_cur.execute('DROP TABLE demo') sl_cur.execute(table) # Checking for table creation accura...
""" 5. Activity Planner The following information is stored in a personal activity planner: Person: person_id, name, phone_number Activity: activity_id, person_id - list, date, time, description Create an application to: 1. Manage persons and activities. The user can add, remove, update, and list both p...
class Collection: class Iterator: def __init__(self, collection): self.__collection = collection self.__id_iterator = iter(self.__collection._data) def __iter__(self): return self def __next__(self): return self.__collection._data[next(self....
from repository.repo import Repo from settings import ROWS, COLS class Service: def __init__(self): self.repo = Repo() self.player = 1 def board(self): return self.repo.board() def empty_board(self): """ Empties board """ self.repo.empty_board() ...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。 例1 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], ...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。 假设只有一个重复的整数,找出这个重复的数。 示例 1: 输入: [1,3,4,2,2] 输出: 2 示例 2: 输入: [3,1,3,4,2] 输出: 3 说明: 不能更改原数组(假设数组是只读的)...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。 你找到的子数组应是最短的,请输出它的长度。 示例 1: 输入: [2, 6, 4, 8, 10, 9, 15] 输出: 5 解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序 分析: ...
''' Ŀ һжǷл Ϊ˱ʾеĻʹ pos ʾβӵеλã 0 ʼ pos -1ڸûл ʾ 1 룺head = [3,2,0,-4], pos = 1 true ͣһβӵڶڵ㡣 ʾ 2 룺head = [1,2], pos = 0 true ͣһβӵһڵ㡣 ʾ 3 룺head = [1], pos = -1 false ͣû...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:根据一棵树的前序遍历与中序遍历构造二叉树。 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / \ 9 20 ...
''' һжǷǸ߶ƽĶ Уһø߶ƽΪһÿڵ ĸ߶Ȳľֵ1 ''' # һʱ ˢɣ ֱͨĸ߶Ƚеݹб𼴿 # ʱ临ӶΪO(NlogN)ռ临ӶΪO(log(N)) class Solution(object): # ȡƽ Ľ def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True else: # ƽһ ȲСЩҶƽ ...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei), 为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。 示例 1: 输入: [[0, 30],[5, 10],[15, 20]] 输出: 2 示例 2: 输入: [[7,10],[2,4]] 输出: 1 ...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 示例 1: 输入:head = [3,2,0,-4], pos = 1 输出:tail connects to node index 1 解释:链表中有...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 ...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 例如 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 其层次遍历结果: [ [3], ...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口 k 内 的数字。滑动窗口每次只向右移动一位。返回滑动窗口最大值。 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 输出: [3,3,5,5,6,7] 滑动窗口的位置 最大值 --------------- -----...
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精 ''' 题目:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例: 现有矩阵 matrix 如下: [   [1,   4,  7, 11, 15],   [2,   5,  8,...
__author__ = 'syedaali' ''' 12/25/2014 This is a small DCIM, or data-center inventory management tool. It stores 3 items, hostname, admin name, and a field called active. Hostname is obvious, it's the hostname. Admin name is the name of a person who is in-charge of the server. Active field should be yes/no, and indica...
############################################################################ # #Write a Python script to merge two Python dictionaries. # ############################################################################ dict1 = {'roll_no' : 1, 'name' : 'Shreya', 'std' : '9th'} dict2 = {'school' : 'xyz', 'college' : 'bvm...
###################################################################### # #Write program using each function. (using lambda function and list.) # ###################################################################### from functools import reduce #1) filter print("filter") My_list = [1,2,3,4] result = list(filter(lambd...
############################################################################### # # Define a function that can accept two strings as input and print the string # with maximum length in console. If two strings have the same length, then # the function should print all strings line by line. # ######################...
############################################################################ # # Write a python program which takes comma separated numbers from user and # print sum of all the numbers. # ############################################################################ from functools import reduce numbers = input("En...
############################################################################ # # Write a Python script to generate and print a dictionary that contains a # number (between 1 and n) in the form (x, x*x). # Sample Dictionary ( n = 5) : # Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # #######################...
""" Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. """ def reverselastk(a, k): index = range(len(a)) ...
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimi...
""" Write a function to find the longest common prefix string amongst an array of strings. """ class Solution(object): def longestCommonPrefix(self, strs): if len(strs) == 0: res = "" elif len(strs) == 1: res = strs[0] else: scan_length = len(strs[0]) ...
""" leetcode Question 27: Distinct Subsequences Distinct Subsequences Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relativ...
""" Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k is always valid, 1 <= k <= array's length. """ import os, sys import numpy as np def getmax(A...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 14th, 2019 This is the solution to calculating 24 based on sequence of numbers provided, and it will only use +, -, *, / operations It needs Python 3 @author: M """ def cal24_v1(q, a, cache={}): def equivalent(a, b): if abs(a-b) < 1...
""" Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? Lessons: 1) The trick is to use...
""" Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1...
""" Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. """ def getIntervals(S): queue = [] for i in range(len(S)): if len(queue)==0: start = 0 else: start = queue[-1][1]+1 ...
""" Spiral Matrix I Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. """ def nextMove(move): moves = ['right','down','left','up'] ...
""" Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. """ def isPalingdrom(x): # x = "abba" x = x.replace(" ","") len_ = len(x) if len_ <=...
# Inspired by https://www.pythonforbeginners.com/code-snippets-source-code/script-password-generator import string from random import * charset = string.ascii_letters + string.digits def password(n): print("Password of length ", n, ": ") # See link above for source password = "".join(choice(charset) for x in r...
# <user story> as an airport assistant I want to be able to create a flight_trip with a specific destination # <user story> as an airport assistant I want to be able to create a flight_trip with a specific destination class Flight_trip: def __init__(self, flight_number, destination, origin, duration, passenger_li...
import datetime def convert_date_to_es_format(date): try: datetime.datetime.strptime(date, '%d/%m/%Y') except ValueError: raise ValueError("Incorrect data format, should be DD/MM/YYYY") date_list = date.split('/') new_date = date_list[2] + '-' + date_list[1] + '-' + date_list[0] ...
'''z={"sb":"hello",23:32,"zhaohuaran":"shabi"} print z["sb"] print z[23] print z["world"]''' print "--------------------------------" l=range(97,123) s=list('abcdefghijklmnopqrstuvwxyz') def m(a,b): return a,b lc=map(m,s,l) print lc print "--------------------------------" '''s=range(97,123) d={} i=0 while i<len(s): ...
j=1 while j<10: i=1 while i<10: print i*j, i=i+1 j=j+1 print "" print "------------------------" j=1 while j<10: i=1 while i<10: if j>=i: print i*j, else: print (" "), i=i+1 j=j+1 print "" print "-----------------------------" j=1 while j<10: print "*", i=2 while i<10: if j==i or j==9: ...
# 5 - Faça um Programa que converta metros para centímetros. metros = int(input('Digite a quantidade de metros: ')) conversor = metros * 100 print(metros, ' metros, são ', conversor, ' centimetros.')
#21. Write a NumPy program to create a vector of length 10 with values evenly distributed between 5 and 50. import numpy as np v = np.linspace(10, 49, 5) print("Length 10 with values evenly distributed between 5 and 50:") print(v) #22. Write a NumPy program to create a vector with values from 0 to 20 and change the sig...
arr=list() n=int(input("enter the no. of elements ")) for i in range(0,n): arr.append(int(input("num: "))) sum =int(input("enter the sum of two numbers ")) sorted(arr) l=0 h=n-1 c=0 while(l<h): if(arr[l]+arr[h]==sum): print("two numbers whose sum matches the given sum are",arr[l],arr[h]) c=1 ...
n= int(input()) l=1 r= n*n+1 print("pattern is -") for i in range(0,n): for j in range(0,i): print(" ", end="") for j in range(i,n): print(str(l)+"*", end="") l=l+1 for j in range(i,n): print(r, end="") if(j<n-1): print("*", end="") r=r+...
def find_group(programs, program, group): group |= {program} for p in programs[program]: if p not in group: group |= find_group(programs, p, group) return group programs = {} with open('input/day12_input', 'r') as f: for program in f: p = program.strip().split('<->') ...
UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 step = { UP: lambda pos: [pos[0] - 1, pos[1]], RIGHT: lambda pos: [pos[0], pos[1] + 1], DOWN: lambda pos: [pos[0] + 1, pos[1]], LEFT: lambda pos: [pos[0], pos[1] - 1], } def char_at(diagram, pos): return diagram[pos[0]][pos[1]] if 0 <= pos[0] < len(diagram) and 0...
""" Puzzle input: To continue, please consult the code grid in the manual. Enter the code at row 2947, column 3029. """ def get_code(row, col): code = 20151125 r = 2 while True: r_i = r c_i = 1 while r_i > 0: code = (code * 252533) % 33554393 if r_i == ro...
def isint(string): try: int(string) return True except: return False def execute_assembunny(instructions, registers): pc = 0 while pc < len(instructions): inst = instructions[pc] if inst[0] == 'cpy': registers[inst[2]] = int(inst[1]) if isint(inst[1])...
from itertools import groupby INVALID_CHARACTERS = (ord("i"), ord("l"), ord("o")) def is_run(c): return c[1] == c[2] - 1 and c[0] == c[2] - 2 def is_valid(password): # Passwords cannot contain "i", "l", or "o" all_valid_chars = not any(c in password for c in INVALID_CHARACTERS) # Check for double le...
# String # String di python dapat dideklarasi dengan single ('') atau double ("") quote, # sebab python sangat sensitif dengan spasi, # maka gunakan tiga single atau double quote untuk mendeklarasikan multiline string theString = "Hello World" thesMultiLineString = """Lorem ipsum dolor sit amet, consectetur adipisci...
"""nested_list = [['a', 'b', 'c'], [1, 2, 3]] # Use indexing to access the second element in the first nested list element_within_nested_list = nested_list[0][1] print(element_within_nested_list)""" """Slicing a nested list""" start = 10 end = 21 num_list = list(range(start, end)) overall_list = [['a', 'b', 'c'], ...
import csv import numpy as np ERROR_COLUMN = 1 TEST_SET = 0 TRAINING_SET = 1 class ExemplarProvider: """ This class provides and holds data for the sampler. It opens up the data set file, then deals with any necessary transformations to the data set. """ def __init__(self, filename): sel...
# "my name is Wayne" # 1 # -1 # 0 # 1.1 # -1.1 # 0.0 # True # False # a = str # b = int # c = float # d = bool # e = "My name is Wayne" # f = 1 # g = 1.1 # h = True # str1 = "Hello" # str2 = "World" # str3 = str1 + str2 # print(str3) # a = "Hello" # b = a # print(b) # c = "Hello" # d = 1 # print(d) # print(ty...
import random class RPSGame: choice = ['rock', 'scissors', 'paper'] def main_menu(self): username = self.greet() starting_rating = self.check_user_in_rating(username) choice_list = self.get_choices() print("Okay, let's start") while True: user_c...
#Digite o nome de um cidade e eu te digo se ela começa com Santo cidade = input('Digite o nome da sua cidade natal:').strip() div = cidade.upper().split() print('A sua cidade natal Começa com Santo? {}'.format('SANTO' in div[0]))
import math ang = float(input('Informe o valor do ângulo: ')) seno = math.sin(math.radians(ang)) print('O ângulo de {} tem o seno de {:.2f}'.format(ang, seno)) cosseno = math.cos(math.radians(ang)) print('O ângulo de {} tem o cosseno de {:.2f}'.format(ang, cosseno)) tangente = math.tan(math.radians(ang)) print...
largura = float(input('largura:')) altura = float(input('altura:')) area = largura * altura litro = 2 tinta = area / litro print('nessa parede será necessário {}L de tinta'.format(tinta))
def merge_sort(array): """ merge sort """ if len(array) > 1: mid = len(array) / 2 left = array[0:mid] right = array[mid:] merge_sort(left) merge_sort(right) # merge l, r = 0, 0 for i in range(len(array)): if (l < len(left)): ...
import turtle mp = turtle.Pen() mp.speed(0) #放置图案居中 mp.penup() mp.goto(140,86) mp.pendown() #for循环绘制勾玉 for j in range(3): #双曲线绘制勾 mp.fillcolor("black") mp.begin_fill() mp.dot(100,"black") mp.backward(50) mp.right(90) mp.circle(100,-90) mp.circle(50,150) mp.end_fi...
import abc from typing import Union class DataType(metaclass=abc.ABCMeta): """ Abstract parent class for all data types. """ # Constants for all data types. INT = 1 STRING = 2 ARRAY = 3 # ------------------------------------------------------------------------------------------------...
print('''Welcome to use Tony's tool box given by Nick Fury! I'd like to introduce to you proudly that this tool box has three fantastic functions! The first one is to encode or decode using base64 method The second one is to create a dictionary via keys and values given here, print JavaScript Object Notation, and provi...
""" Random Variables """ import random # random is default package # for i in range(3): # print(random.random()) # random() by default print values between 0 and 1 # for i in range(7): # print(random.randint(1, 10)) # randint() allows us to choose the random variable range """ Exercise """...
""" FUNCTIONS """ # def hello_python(): # print('Hello world') # print('How are you?') # # # print('Good Morning') # after function definition leave 2 blank lines and continue (PEP 8: E305 expected 2 blank lines after class or function definition) # hello_python() # print('Thank You!') """ Functions with p...
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. f1...
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? x = 2520 # can start here because any number smaller than this won't meet half the requirements while x % 20...
#!/usr/bin/env python # coding: utf-8 # In[9]: a=list(input("Enter the number : ")) i=-3 while abs(i)<len(a): a.insert(i,",") i-=4 s= ''.join(a) print("The Number In International System Is :",s) # In[ ]: # In[ ]:
#list classes = [] #asking for all of the classes separated by a comma class_name = (input("Please enter the names of all of the classes you are taking, separate with a comma: ")) #prints this message to the user print ("Here are the classes you are taking: ") #splits the inital input by the comma (and a space) an...
matrix = [] for _ in range(5): row = map(int, raw_input().split()) matrix.append(row) row, column = 0, 0 for _row in range(5): for _column in range(5): if matrix[_row][_column] == 1: row, column = _row, _column break print (abs(row - 2) + abs(column - 2))
from __future__ import print_function from node import NodeD as Node import random class DList: def __init__(self): self.head = Node() def insert(self, pos, data): node = Node() node.set_data(data) if self.head.get_data() is None: self.head = node else: if pos == 0: node.set_next(self.head) ...
closing = ( ')', '}', ']') opening = ('(', '{', '[') brackets = opening + closing eq = { '(': ')', '[': ']', '{': '}' } def balanced_symbols(line): stack = list() is_balanced = True for c in line: if c not in brackets: continue elif c in opening: stack.append(c) elif c in closing: paren = stack.pop() ...
# Create a function that prints a triangle like this: # * # *** # ***** # ******* # ********* # *********** # # It should take a number as parameter that describes how many lines the triangle has def mistery_triangle(lines): i = 1 while i <= lines: print(" " * (lines - i), "*" * (...
# Create a method that decrypts texts/encoded_zen_lines.txt def decrypt(file_name): decrypted = "" text = open(file_name, "r") encrypted = text.read() text.close() for lines in encrypted.splitlines(): for chars in lines: if chars != ' ': decrypted += chr(ord(cha...
# Create a method that decrypts the texts/duplicated_chars.txt def decrypt(file_name): decrypted = "" text = open(file_name, "r") encrypted = text.read() text.close() for lines in encrypted.splitlines(): if len(lines) > 2: for i in range(0, len(lines), 2): decr...
# Create a student Class # that has a method `add_grade`, that takes a grade from 1 to 5 # an other method `get_average`, that returns the average of the # grades class Student(): grade = 0 average = 0 grades = [] def __init__(self, student_name): self.student_name = student_name def ad...
q = [4, 5, 6, 7] # get the 3rd element of q print("the 3rd element:", q[2])
# Write a Person class that have a name and a birth_date property # It should raise an error of the birthdate is less than 0 or more than 2016 class Big_mistake(Exception): print('[ *** Nagyon - nagyon - nagyon - nagyon - nagy hiba! *** ]') class Person(): def name(self, first_name, last_name): sel...
af = 123 # create a function that doubles it's input # double af with it def dubles(number): print("duble number: ", 2 * number) dubles(af)
# Adds a and b, returns as result def add(a, b): return a+b # Returns the highest value from the three given params def max_of_three(a, b, c): return max(a, b, c) # Returns the median value of a list given as param def median(pool): if len(pool) % 2 == 0: return (sorted(pool)[len(pool)//2-1] + sor...
# Create an "elevator" class # The class should track the following things: # - elevator position # - elevator direction # - people in the elevator # - add people # - remove people # # Please remeber that negative amount of people would be troubling # import view_elevator_template class Elevator(): def e...
# 9. Given a string, compute recursively a new string where all the # adjacent chars are now separated by a "*". def magic_string(string): if len(string) <= 1: return string[0] else: return string[0] + '*' + magic_string(string[1:]) print(magic_string('1234567890'))
a = [-2, 1, -3, 4, -1, 2, 1, -5, 4] max1 = a[0] maxrr = a[0] for i in range(1, len(a)): maxrr = max(a[i], maxrr + a[i]) max1 = max(max1, maxrr) print(max1) # 3rd # https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3285/
class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min = [] def push(self, x: int) -> None: if self.stack == []: self.min.append(x) self.stack.append(x) else: if x <= ...
#Bo Cen and Canopus Tong #Lab Section D03 #Lecture Section A1 def cracker(pair): # Decrypt a encrypted text. ALL_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"] new_text = "" if len(pair) == 1: # Check if Key is missing. new_tex...
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def insert(self,item): self.items.insert(0,item) def pop(self): return self.items.pop() def ...
# typical mergeSort with inversion modifications def count_inversions(lst): count = 0 # initialize inversion implementation, set count to zero mid = len(lst) // 2 if len(lst) > 1: lefthalf = lst[:mid] righthalf = lst[mid:] count += count_inversions(lefthalf) # add every coun...
x = input("username : ") y = input("password : ") if x == "adimasfachri" and y == "paramore": print("Login Berhasil") else: print("Login gagal") "halo guys"
x = 2 y = "2" z = True if type(x) is int: print("Integer") if type(y) is str: print("String") if type(z) is bool: print("Boolean") if (True or True and False): print("True") else: print("False") if ((True and False) and (True or False) or (False and False)): print("True") el...
# Palindrome Exercise string = input("Enter a word: ") if string.lower() == string[::-1].lower(): print("'%s' is a palindrome!" % string) else: print("'%s' is not a palindrome." % string)
import json import requests response = requests.get('https://raw.githubusercontent.com/everypolitician/everypolitician-data/master/countries.json') countries = json.loads(response.content) print(countries[0].keys()) print(len(countries)) #Pick a country. print(countries[5]) #Extract the URL for the JSON data about ...
days = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] print(type(days)) # <class 'list'> print(days[3]) # Thur print(len(days)) # 6 days.append("Sun") # list에 Sun 추가. print(days) print(len(days)) days.reverse() # List의 순서를 반대로 print(days) # mutable =함수에서 변경 가능 값 # immutable = 변경 불가능한 값
from tkinter import * window = Tk() window.title("drop Down Menu") def funct(): pass #Creating a root menu to insert all the sub menus root_menu = Menu(window) window.config(menu = root_menu) #creating sub menu in the root menu file_menu = Menu(root_menu) # it initializes a new su menu in the root menu root...
def find_sum_pair(lst, N): """ lst: list of sorted integers N: int Given a list of sorted integers, e.g. [1, 3, 5, 7], and an integer N, return true if there is a pair of integers in the list that sum up to N. If there is no pair, return false. Examples: Input: [1, 2, 4, 5, 6], N = 8 Outpu...
#!/usr/bin/env python import sys import re isNumber = '^[1-9][0-9]*\.?[0-9]*([Ee][+-]?[0-9]+)?$'; if len(sys.argv) != 3: print("Error: two arguments required.") print("") print("Usage: {} <arg1> <arg2>".format(sys.argv[0])) exit(0) if not re.search(isNumber, sys.argv[1]): print("Error: the first...