text
stringlengths
37
1.41M
string,v =input().split() v=int(v) for i in range(v): print(string)
str=input() n=False m=False for i in str: if(i.isdigit()==True): m=True if(i.isalpha()==True): n=True if(n and m): print("Yes") else: print("No")
# Version 1 import psycopg2 import psycopg2.extras try: connection = psycopg2.connect(user = "postgres", password = "password", host = "localhost", port = "5432", dbname = "gtd")...
class Solution: def isValid(self, s: str) -> bool: a=[] for i in s: if '['==i or '('==i or "{"==i: a.append(i) else: if len(a)==0: return False if '}'==i: if a.pop() !="{": ret...
# Definition for singly-linked list. import json class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: hhead=ListNode(0,head) nextH=hhead.next root=head su...
names = ["Arvind", "Bala", "Shiva", "Dinesh"] # Mutable #Indexing [] # print(names[0]) #valid # print(names[4]) #IndexError: Index out of range # Mutable # print("Im printing from line number 8 of list {}".format(names)) # names[0] = "Ganesh" # print(f"Im printing from line number 10 of list {names}") # list methods...
# new list l1 = [1, 2, 3, 3, 5, 5, 5, 5] # print(l) #append # word = "Animal" # print(dir(l)) # l.append(word) # print(l) # new_list = l.append(word) This will return None #pop # print("line number 14", l) # r = l.pop() # print("line number 16", l) # print(r) # print(l.pop(3)) # returns the removed element of th...
name = "shiva\n" # to get the length # print(name) #len() # print(len(name)) #INDEX Shiva # 01234 #to get the first element # print(name[2]) # upto but not including # print(name[0:3]) # reverse a string # print(name[::-1]) #Indexing is not possible # name[0] = "R" # print(name) # dir() # print(dir(name...
name = "Ananya" #len to return the length of a given item # print(len(name)) # #index A N A N Y A # 0 1 2 3 4 5 # print(name[::]) # print(name[:]) # print(name[::-1]) # reverse a string in python # if, elif , else #if # user_input = int(input("Enter your age: ")) # if user_input == 50: # print("Valid") ...
""" Given a set of start and end tuples find the minimum number of meeting rooms required for hosting all the meetings Time Complexity = O(NlogN) {time to sort the input} Space Complexity O(N) """ """ Solution 1 with stacks . """ def meeting_rooms_1(timings): starts = sorted([t[0] for t in timings]) ends =...
# coding: utf-8 class Graph(object): def __init__(self, graph_dict=None): if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict def vertices(self): """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): ...
password_to_change = input() command = input() while command != "Done": if command == "TakeOdd": password_to_change = password_to_change[1:len(password_to_change):2] print(password_to_change) elif command.split()[0] == "Cut": index = int(command.split()[1]) length = int(comman...
phrase = tuple(input()) unique_characters = set(phrase) for char in sorted(unique_characters): print(f"{char}: {phrase.count(char)} time/s")
import sys first_list = input() num = int(input()) new_list = first_list.split() min_size = sys.maxsize removal = "" last_list = "" for j in range(num): smallest = min_size for i in new_list: if int(i) < smallest: smallest = int(i) removal = str(smallest) new_list.remove(r...
#empty list empty=[] print("This is an empty list: "+ str(empty)) #list of strings acronyms = ["LOL","IDK","TBH"] word="tada" print("This is a list of acronyms: "+ str(acronyms)) print("This is the last item in list: "+acronyms[len(acronyms)-1]) ## adding to list print("\n\n") acronyms.append("TGIF") acronyms.append(...
def spin_words(sentence): res = "" words = sentence.split() for word in words: if len(word) >= 5: res += word[::-1] else: res += word res += " " return res[:-1]
N = input() number_set = input() total = 0 for i in range(int(N)): total += int(number_set[i]) print(total)
''' Repeating Characters ''' T = input() for i in range(int(T)): S = input() # Split the string S = S.split() # Setting the repeat variables R = S[0] # Setting the paragraph variables P = "" for j in range(len(S[1])): P += S[1][j] * int(R) print(P)
def lone_tally_check(p): """ standard evaluation method, checks each boxes tally set to see if there is only one possible value left for that box. :param p: the puzzle """ # map = p.box_map progress = False # cycle through every box in the puzzle for key, box in p.box_map.items(): ...
""" Sort file based on a column. """ import sys def parser(): return { 'help': 'Sort file based on a column.' } def add_arguments(parser): """ Parse arguments Args: parser (argparse.ArgumentParser) """ parser.add_argument('-dt', "--datatype", action="store", type=str, de...
import MapReduce import sys mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: order_id # value: whole record key = record[1] value = record mr.emit_intermediate(key, value) def reducer(key, value): # key: order_id # valu...
import sys sum_int = 0 while True: line_str = sys.stdin.readline() if not line_str: break sum_int += int(line_str) print(sum_int)
#!/usr/bin/env python "在windows 7下每次运行打印不同的结果" import threading import time COUNT_INT = 0 def adder(): "间隔地给COUNT_INT加1" global COUNT_INT COUNT_INT += 1 time.sleep(0.5) COUNT_INT += 1 def main(): global COUNT_INT listThread = [] for i_int in range(100): Thread = threading.Thread(target=adder) listThr...
#!/usr/bin/env python """ 分隔字符串或文本文件并交互的进行分页 """ def more(text_str, num_lines=15): lines = text_str.splitlines() while lines: chunk = lines[: num_lines] lines = lines[num_lines: ] for line in chunk: print(line) if lines and input('More?') != '': break if __name__ == '__main__': import sys if len(sys.a...
#!/usr/bin/env python "每次都打印200,因为共享资源的访问已经同步化" import threading import time COUNT_INT = 0 def adder(count_int_mutex): "间隔地给COUNT_INT加1" global COUNT_INT with count_int_mutex: COUNT_INT += 1 time.sleep(0.5) with count_int_mutex: COUNT_INT += 1 def main(): global COUNT_INT count_int_mutex = threading.Lo...
#!/usr/bin/env python "利用bool列表在父线程中探知子线程何时结束" import _thread as thread MUTEX = thread.allocate_lock() NUMS_THREAD_INT = 10 LISTBOOL = [False for i_int in range(NUMS_THREAD_INT)] def counter(id_int, count_int): "数数" for i_int in range(count_int + 1): MUTEX.acquire() print('[{}] -> {}'.format(id_int, i_int)) ...
# Python program to print # red text with green background from colorama import Fore, Back, Style print(Fore.BLUE + 'some red text') print(Back.CYAN + 'and with a green background') print(Style.BRIGHT + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')
import requests # # build URL # path_url = 'http://api.postcodes.io/postcodes/' # argument = 'CR03SW' # post_codes = requests.get(path_url + argument) # # print(post_codes) # #turn this into a dictionary # dict_response = post_codes.json() # # #getting out data # print(dict_response.keys()) # # #getting the response...
def length_of_longest_substring(s: str): length: int = 0 last_index = {} n: int = len(s) l: int = 0 r: int = 0 while l < n and r < n: c = s[r] if c in last_index: l = max(l, last_index[c] + 1) last_index[c] = r length = max(length, r - l + 1) ...
class Calculator: def __init__(self,lis): self.tot=0 self.lis=lis def sum(self): self.tot=sum(self.lis) print(self.tot) def avg(self): if self.tot!=0: self.av=self.tot/len(self.lis) else: ...
class Ksztalty: def __init__(self, x, y): self.x=x self.y=y self.opis = "To będzie klasa dla ogólnych kształtów" def pole(self): return self.x * self.y def obwod(self): return 2 * self.x + 2 * self.y def dodaj_opis(self, text): self.opis = text de...
import time N = int(1e6) start = time.time() # Inefficient: creaend a list of length N in memory, # then iterate over it for k in range(N): pass end = time.time() print 'Iterating through a list of', N, 'elements took', \ round(1000*(end - start),2), 'milliseconds.' start = time.time() for l in xrange(N): ...
# -*- coding: utf-8 -*- """ Created on Mon Jun 21 17:14:48 2021 @author: chung """ semi_annual_raise = 0.07 r = 0.04 total_cost = 10**6 down_payment = 0.25 * total_cost months = 36 annual_salary = float(input("Annual Salary: ")) def total_save(portion_saved): total_saved = 0 monthly_salary = ...
#1 x = int(input("sum_of_elements: ")) num = 0 full_list = [] even_list = [] while True: full_list.append(num) if num%2 == 0: even_list.append(num) elif len(even_list) == x: print(full_list) print(even_list) print(sum(even_list)) break if num == 0: num = 1...
class BinarySearch: def __init__(self,input_array): #Конструктор класса self.array=input_array self.array_len=len(self.array) self.Right=self.array_len-1 self.Left=0 self.Stop_Search=False self.Success=False def Step(self,N): #выполняет один шаг ...
# data = [ # ['ram', 'sita', 'gita', 'hari'], # ['laxmi', 'binita', 'anish', 'rahul'], # ['sophia', 'kamal', 'sunita', 'test'], # # ] # # for names in data: # for name in names: # print(name) # for name in data: # print(name) # # for a in range(10): # print(a) # # x = 1 # # while x < ...
import requests import csv from bs4 import BeautifulSoup as Soup url = "https://university.graduateshotline.com/ubystate.html#NC" fieldnames = ['Name', 'State', 'Website'] # CSV file Open def csv_file(): with open('US Universities by State.csv', 'w') as csvfile: writer = csv.DictWriter(csvfi...
''' This outline will help solidify concepts from the Mathematical Operators lesson. Fill in this outline as the instructor goes through the lesson. ''' #1) Make two string variables and use the + operator to combine them into #one new variable. var = " Hello" + " there" #2) Make two int variables and use the + oper...
import requests import io from os import path import pandas as pd import plotly.graph_objs as go def fetch_data(path_to_data, file_name='../data/latest_crime_data.csv'): """ Request the dataset from https://www.ethnicity-facts-figures.service.gov.uk/crime-justice-and-the-law/policing/number-of-arrests/. ...
# Import necessary libraries import numpy as np import mnist import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense from keras.utils import to_categorical #Load the dataset train_images = mnist.train_images() train_labels = mnist.train_labels() test_images = mnist.test_image...
# -*- coding: utf-8 -*- import sys from Tkinter import * app = Tk() app.title("Aplicacion grafica en python") etiqueta = Label(app, text="Hola mundo!!!") boton = Button(app, text="OK!!") etiqueta2 = Label(app, text="otra etiqueta") etiqueta.pack()#si no se agrega la etiqueta.pack() el controlo no se agrega a la ventana...
#domino con cadenas print 'dominocadenas.py' def jugardomino(ficha1,ficha2): fichaa=ficha1.split('-',1) fichab=ficha2.split('-',1) #print fichaa[1] posible='Si es posible' noposible='No es posible' print fichaa[0] if (fichaa[0]==fichab[0]): print posible elif (fichaa[0]==fichab[1]): print posible elif (fic...
from typing import Optional class State: """ This class represents a State of an automaton """ def __init__(self, name: Optional[str] = None): self.name: str = name def __eq__(self, other) -> bool: if not isinstance(other, type(self)): return NotImplemented ret...
# 1 Intro to List print("\n# 1") a = [1, 2, 3,] print(a) b = ['a', 'b', 'c',] print(b) c = [1, 'x', 10, 'abc', 10.0,] print(c) # 2 Indexing and Slicing print("\n# 2") a = ['a', 'b', 'c', 'd', 'e', 'feg',] print("a:", a) print() print("a[3]:", a[3]) print("a[2:5]:", a[2:5]) print("a[-3:]:", a[-3:]) print("a[-1][:-2]:",...
# 1 Odd, Even print("\n# 1") a = int(input("Enter a number: ")) if a%2 == 0: print("It's even number!") else: print("It's odd number!") # 2 +, - / Odd, Even print("\n# 2") a = int(input("Enter a number: ")) if a > 0 and a %2 == 0: print(f"{a} is positive even number!") elif a < 0 and a%2 == 0: pri...
numbers = [2,4,5,6,4,4,2,34,31,32,14,6] def merge_sort(arr): if len(arr)<2: return arr mid = len(arr)//2 left_arr = merge_sort(arr[:mid]) right_arr = merge_sort(arr[mid:]) l = r = 0 merged_arr = [] while l<len(left_arr) and r<len(right_arr): if left_arr[l] < right_arr[r]:...
# def my_function(x): # return 5 * x # print(my_function(3)) # print(my_function(5)) # print(my_function(9)) def rectangle(p,l): luas=p*l keliling=2*p + 2*l return luas, keliling p = int(input("panjang = ")) l = int(input("lebar = ")) print(rectangle(p,l))
# passing arguments to decorator def decorator_with_args(decorator_args1, decorator_args2, decorator_args3): def decorator(func): def wrapper(function_args1, function_args2, function_args3): print("The wrapper can access all the variables\n" "\t from the decorator maker:{...
""" generating random graphs ER and in the in-degree distribution """ import math import matplotlib.pyplot as plt import sys sys.path.append("../../_degree_distributions_for_graphs") import ddg p = 0.2 #probability directed edge from i to j n = 5000 # count nodes er_graph = ddg.make_complete_graph_p(n, p) in_degre...
class Solution: def isUgly(self, num): reducedNum = num while reducedNum >= 2: if reducedNum % 2 == 0: reducedNum /= 2 else: break while reducedNum >= 3: if reducedNum % 3 == 0: reducedNum /= 3 else: break while reducedNum >= 5: if reducedNum % 5 == 0: reducedNum /= 5 else...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def getInOrder(root): if root is None: return [] left = getInOrder(root.left) this = [root.val] right = getInOrder(root.right) return left + this + right class Solution: def lowestCommonAncestor(self, root, p, q)...
#Start with a number n > 1. Find the number of steps it takes to reach one #using the following process: If n is even, divide it by 2. If n is odd, #multiply it by 3 and add 1. import sys import argparse import time def timeit(method): def timed(*args, **kw): ts = time.clock() result = method(*a...
import unittest class Snap(object): def __init__(self, val): self.next = [] self.val = val def dectCircle(self): # dfs with pruning visited = set() if dfs(self, visited, []): return True else: return False def dfs(snap, visited, path): for friend in snap.next: if friend in visited: continu...
# -*- coding: utf-8 -*- """ Created on Tue Jul 16 14:16:09 2019 @author: IST """ def list_ends(a_list): return [a_list[0], a_list[len(a_list)-1]] a = [1,2,3,4,5] print (list_ends(a))
# -*- coding: utf-8 -*- """ Created on Wed Jul 17 10:23:38 2019 @author: IST """ def fibonacci (eleNum): i= 1 if eleNum == 0 : fib = [] elif eleNum ==1 : fib =[1] elif eleNum ==2: fib = [1,1] elif eleNum > 2: fib = [1,1] while i < eleNum - 1: fib.append(...
#1. prediction: 5 def a(): return 5 print(a()) #2. prediction: 10 def a(): return 5 print(a()+a()) #3. prediction: 5 def a(): return 5 return 10 print(a()) #4. prediction: 5 def a(): return 5 print(10) print(a()) #5. prediction: 5 nothing def a(): print(5) x=a() print(x) #6. prediction:...
singer = input("選擇歌手:") song = input("選擇歌曲:") class Data: def __init__(self,singer,song): self.singer = singer self.song = song def printSinger(self): if singer == "周杰倫" : print("你選周杰倫") elif singer == "陳奕迅" : print("你選陳奕迅") else : print("還沒儲存這個歌手") def prin...
name =input("打名字啦,哪次沒名字:") gender =input("性別:") email =input("電子信箱:") dinner =input("晚餐吃:") if name.count("*") != 0 : print("不要亂打啦") else : print(f"名字:{name}") print(f"性別:{gender}") print(f"電子信箱:{email}") print(f"晚餐吃:{dinner}")
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ s = str(x) y = s[: : -1] if y == s: return True else: return False # ========================================= solution = Solution() x1 = 121...
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ times = 1 if n <= 1: return times if n >= 2: times1 = self.climbStairs(n - 1) times2 = self.climbStairs(n - 2) times = times1 + t...
# import copy # nums = [1,2,3] # list = copy.copy(nums) # list.append(4) # print nums # print list nums = [1,2,3] list = nums list.append(4) print nums
class Animal(object): def eat(self): print 'I am eating' def drink(self): print 'I am drinking' def sleep(self): print 'I am sleeping' class Bird(Animal): def fly(self): print 'bird can fly!!!' class Person(Animal): def __init__(self): self.head = Head(...
#What do the following functions do? #random - generates ramdom float between 0-1 #uniform - generates random float between two numbers #randint - generates ramdom integer between two numbers #Import random here: from random import uniform, randint #Print a random Float between 0.0 & 1.0 print(uniform(0,1)) #Print a...
#The user enters a yes or no question #The computers returns a random Magic 8 Ball Statement to the awnser. #Here are the statments it should select randomly from to awnser the question. ''' Yes, Definatly It is very likely Maybe That's pretty unlikely Thats impossible Why do you ask me a question you already know the ...
from visdom import Visdom class Plot: def __init__(self, name_x: str, name_y: str, viz: Visdom): """ this class represents a visdom plot. It contains the name of the x axis and the y axis which define the type of the plot :param name_x: the name of the x axis :param name_y:...
import numpy as np # Read Values from csv into 2 Lists: X & Y def ols(file): X = [] Y = [] csv = np.genfromtxt(file, delimiter=",") X = csv[:,1] Y = csv[:,2] X[np.isnan(X)]=0 Y[np.isnan(Y)]=0 # Mean x & y x_mean = np.mean(X) y_mean = np.mean(Y) # Calculate Intercept & Slope ...
beatles = ["paul", "john", "ringo"] print(beatles[0]) print(beatles[0:2]) print(len(beatles)) beatles.append("George") print(beatles) beatles[0] = "PAUL" print(beatles) del(beatles[2]) print(beatles) #CRUD # most have it when creating elements # Create -> list.append(element) # Read -> list[index] # Update ->...
phones = {"john": 4019, "paul": "4121", "dave": "9081", "bob": "4322"} type(phones) print(phones) # do a crud on a dictionary # keys most be unique # What is the phone number of paul #read print(phones["paul"]) #create update is the same phones["paul"]= "1212" print(phones["paul"]) #removing an element del(pho...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1 , l2 ) : res = ListNode(0) next = res add = 0 while True : if l1 == None and l2 == None : ...
import math def function(x, y): return (-2*x-y) def euler_explicit_1(x_0, y_0, x, h): n = int((x - x_0)//h + 1) y = y_0 for i in range(1, n+1): del_y = h*function(x_0, y) y = y + del_y x_0 = x_0 + h print(f"y' = {function(x_0,y)}\nh*y' = {h*function(x_0,y)}") ...
""" This file computes the file for the trajectory of the person """ import os import re from jsonfilereader import JsonReader, split_json, pixel_fall, height_person from helper import * def compute_cm(body_parts): """ Given: body_parts – list of body parts position with the order nose, shoulder,elbow, wr...
sentence="Zeven Zottegemse zotten zullen zes zomerse zondagen zwemmen zonder zwembroek." myList=sentence.split() print(myList) length=len(myList) print(length) def reverse(s): return s[::-1] print(reverse('help')) l1=[[1,2],[2,5],[3,6]] print(l1 [1]) l1 [1] print("1".isdigit()) print(False) d...
# Given a, b, c for a quadratric expression ax2 + bx + c = 0. # Write a function getX that returns the larger of the values for X, # i.e. given x1 = -2 and x2 = 5, getX should return 5. # Formulas # x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a) # x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a) # Solution. import...
import random def shuffleDeck(): suits = {'\u2660','\u2661','\u2662','\u2663'} ranks = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'} deck = [] for suit in suits: for rank in ranks: deck.append(rank + ' ' + suit) random.shuffle(deck) # Now shuffle...
import math import numpy as np import itertools from collections import deque from operator import itemgetter def accumulate(edge_array, img_size, threshold=300): """ Main hough transform function. This is an optimized hough transform which doesn't blindly bruteforce every possible radius throughout the image. I...
# Write a program that detects the ID number hidden in a text. # We know that the format of the ID number is: # 2 letters, 1 digit, 2 letters, 2 digits, 1 letter, 1 digit (For example: AA4ZA11B1). # import re text = "AABZA1111AEGTV5YH678MK4FM53B6" pattern = r"\w\w\d\w\w\d\d\w\d" re.search(pattern, text) for...
name = "Jose Antonio Amieva" country = "Mexico" age = 25 hourly_wage = 1000000 satisfied = True daily_wage = 100000000000 print("My name is " + name + ", I have " + str(age) + " years old. I am actually living in " + country + " and my wage is " + str(hourly_wage) + " per hour.") print(f"my daily wage is ${daily_...
import itertools # The list of candies to print to the screen candyList = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Swedish Fish", "Skittles", "Hershey Bar", "Starbursts", "M&Ms"] # The amount of candy the user will be allowed to choose allowance = 5 # The list used to store all of the ...
import csv file = './netflix_ratings.csv' f = open(file) csv_f = csv.reader(f) inputName = input("What tv show or movie do you want to search for? ") rating = "" user_rating = "" a = False for row in csv_f: if row[0] == inputName: rating = row[1] user_rating = row[5] a = True if a =...
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print("Answer is")print(num1 + num2) print("This calculator is made by Vinayak Handa") print(" 20 april 2021")
class Customer: def __init__(self, email): self.email = email self.age = 0 self.last_name = "" self.first_name = "" self.password = "" self.card_number = "" self.security_code = "" def input_age(self): while True: try: ...
#!/usr/bin/env python import itertools import num2words import re import sys EPS = '<epsilon>' # [start, end] def foo(start, end): s = 1 for i in range(start, end + 1): words = re.split('\W+', num2words.num2words(i)) # removes delimiters isym = str(i) prev = 0 for isym, osym in itertools.izip_l...
'''year=int(input('enter your year:')) if(year%4==0): print(year,'is leap year') else: print(year,'is not leap year')''' year=int(input('enter your year:')) if(year%100==0): if(year%400==0): print(year,'is leap') else: print(year,'is not leap') else: if(year%4==0): ...
# -*- coding: utf-8 -*- import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm import statsmodels.formula.api as smf #Simple Linear Regression Boston = pd.read_csv('../data/Boston.csv', index_col=0) Boston.columns #medv (median house value), lstat(percent of households with low socioeconomic ...
"""Display Manager: Handles all things relating to Pig's core display features.""" import time def print_main_menu(): """Prints Main Menu""" print("Hello! Welcome to Pig.") print("Rules: \n\tRoll a die to see who goes first, ascending-order-wise.") print("\tRoll until you like the score you currently h...
# QUESTION """ Longest Word Have the function LongestWord(sen) take the sen parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Words may...
import copy import random import numpy as np array = np.zeros((10,2)) def add(value, index): low = 0 high = index mid = int((low + high) >> 1) while (low - high) > 1: #print low, high if value > array[mid]: low = mid mid = int((low + high) >> 1) else: high = mi...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve from sklearn.model_selection import ShuffleSplit #---------------------------------------------------------------------- def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, ...
import time from datetime import date import win32com.client as wc import os from colorama import init, Back, Fore, Style import calendar init() def ns(c): while c!=("s") and c!=("n"): print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ").lower() return(c) def OKI(n): try: ...
import functools import sys def tokenize(s): lst = [] i = 0 while i < len(s): if s[i] == '(' or s[i] == ')': lst.append(s[i]) i += 1 elif s[i] == ';': j = i while j < len(s) and s[j] != '\n': j += 1 i = j ...
# # Σχ. Έτος 2020-21 # Θεόδωρος Ελευθέριος Βασιλικός # Νίκος Καλλίτσης # Παιχνίδι γνώσεων για απόφοιτους του Γυμνασίου © # #Variable για τις λάθος απαντήσεις: pl = 0 # όλα τα functions για τις ερωτήσεις: def Πληροφορική_προσπάθειες(): category1 = input('Πληροφορική ') if category1 == "Ναι" or ca...
# Read thru chapter 5, skipping the section on GASP. # http://openbookproject.net/thinkcs/python/english2e/ch05.html # Do chapter 5 exercises 1-8 in this file. # You'll need this... import math # Exercise 1 def compare(a, b): """ >>> compare(5, 4) 1 >>> compare(7, 7) 0 >>> compare(2,...
class Student: name="name" conf={'exam_max': 30 ,'lab_max':7,'lab_num':10, 'k':0.61} def __init__(self,name,conf): self.name=name self.conf=conf res=[0 for res in range(conf['lab_num'])] res_exam=0 def make_lab(self,m,n): if(m>self.conf['lab_max']): ...
def check_stack(list): temp = [] for i in list: if i == '(': temp.append(i) else: if temp: temp.pop() else: return 'NO' if temp: return 'NO' else: return 'YES' answer = [] for _ in range(int(input())): ...
caseCount = int(input()) #입력받기 def zero_one_count(value): zero_count = [1,0] one_count = [0,1] if value == 0 : print("%d %d"%(zero_count[0],one_count[0])) elif value == 1: print("%d %d"%(zero_count[1],one_count[1])) else: for j in range(2,value+1): zero_count.app...
# 2021 Copyright Dinu Ion-Irinel from docx import Document from docx.shared import Inches from docx.shared import RGBColor # initialize of the document document = Document() # intro informations name = input("Hello, what is your name? : ") phone_number = input("What's your phone_number: ") email = input("Enter your ...
# [2018-08-20] Challenge #366 [Easy] Word funnel 1 # https://www.reddit.com/r/dailyprogrammer/comments/98ufvz/20180820_challenge_366_easy_word_funnel_1/ CHALLENGE_INPUT = { 'leave' : 'eave' , 'reset' : 'rest' , 'dragoon' : 'dragon' , 'eave' : 'leave' ...
# -*- coding: utf-8 -*- """ Created on Thu Dec 07 18:30:03 2017 @author: Otávio Felipe Ferreira de Souza """ import numpy as np import pandas as pd class Usuario(object): def criar_tabela(self): tabela = [] z = raw_input("Digite a funcao Z (Separado ...
#217 # Time: O(n) # Space: O(n) # Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, # and it should return false if every element is distinct. class hashTableSol(): def containDuplicate1(self,nums): ...
#141 # Time: O(n) # Space: O(1) # Given a linked list, determine if it has a cycle in it. # # Follow up: # Can you solve it without using extra space? class ListNode(): def __init__(self,val): self.val=val self.next=None def __repr__(self): return '{}->{}'.format(self.val,re...