text
stringlengths
37
1.41M
class LinkedNode(object): def __init__(self, data): self.data = data self.nextnode = None def print_list(head): temp_head = head while temp_head: print temp_head.data # print temp_head temp_head = temp_head.nextnode print def reverse_list(original_head): head = original_head previous = None while head: print head temp = head.nextnode head.nextnode = previous previous = head head = temp original_head = previous print "ttt" print original_head print previous print "ttt" return previous org = [x for x in xrange(10)] head = LinkedNode(0) temp_head = head for i in xrange(len(org)): temp_head.data = i if i != len(org) - 1: temp_head.nextnode = LinkedNode(0) temp_head = temp_head.nextnode print_list(head) print_list(head) print_list(head) print "asdd", head r=reverse_list(head) print "head", head print "r", r print "reverse" print_list(r)
def is_possible(a, b): return sum(a) == sum(b) def find_diff(a, b): total_equal = 0 for i in range(len(a)): if a[i] > b[i]: total_equal += a[i] - b[i] return total_equal n = int(raw_input().strip()) a = map(int, raw_input().strip().split()) b = map(int, raw_input().strip().split()) if is_possible(a, b): a.sort() b.sort() print find_diff(a, b) else: print -1 """ a = [1, 4, 12, 14, 16] b = [1, 5, 10, 15, 16] print find_diff(a, b) print find_diff(b, a) n = 5 a = [1, 2, 3, 4, 5] b = [-9, -1, 5, 8, 12] print find_diff(a, b) print find_diff(b, a) a= [1, 2, 3] b = [-1, 3, 4] print find_diff(a, b) print find_diff(b, a) a = [1, 4, 12, 14, 16] b = [16, 15, 10, 1, 5] print find_diff(a, b) print find_diff(b, a) """
def mysort(A, p, n): result = [] i = 0 j = p while i < p and j < n: if A[i] < A[j]: result.append(A[i]) i += 1 else: result.append(A[j]) j += 1 while i < p: result.append(A[i]) i += 1 while j < n: result.append(A[j]) j += 1 return result def main(): A = [3,4,7,9,13,1,5,6,8] B = mysort(A, 5, len(A)) A = [3,1,2,3,4,5,6] B = mysort(A, 1, len(A)) A = [1,2,3,4,5,6,2] B = mysort(A, 6, len(A)) print B if __name__ == '__main__': main()
""" Input: [-2, -3, 4, -1, -2, 1, 5, -3] Output: 12 Two subarrays are [-2, -3] and [4, -1, -2, 1, 5] Input: [2, -1, -2, 1, -4, 2, 8] Output: 16 Two subarrays are [-1, -2, 1, -4] and [2, 8] """ Input= [-2, -3, 4, -1, -2, 1, 5, -3] total = sum(Input) left = 0 right = total mx = 0 print Input print total for i in xrange(len(Input) - 1): left += Input[i] right -= Input[i] print i, left, right if abs(left - right) > mx: mx = abs(left - right) print mx
''' 8) Escreva um programa que leia dois números. Imprima a divisão inteira do primeiro pelo segundo, assim como o resto da divisão. Utilize apenas os operadores de soma e subtração para calcular o resultado. Lembre-se de que podemos entender o quociente da divisão de dois números como a quantidade de vezes que podemos retirar o divisor do dividendo. Logo, 20 ÷ 4 = 5, uma vez que podemos subtrair 4 cinco vezes de 20. ''' dividendo = int(input('Informe o dividendo: ')) divisor = int(input('Informe o divisor: ')) contador = 0 while dividendo >= divisor: resto = dividendo - divisor dividendo -= divisor contador += 1 print(f'\nDivisão inteira: {contador} \nResto: {resto}')
'''2) Faça um programa para escrever a contagem regressiva do lançamento de um foguete. O programa deve imprimir 10, 9, 8, ..., 1, 0 e Fogo! na tela.''' import time quantidade = 10 numeros = list(range(1,quantidade+1)) while len(numeros) > 0: print(numeros.pop()) time.sleep(1) print('0... Fogo!')
#Midterm Exam in Your Home_2_안예림 #각 돌은 순서대로 1~N까지 번호가 붙어 있으며,2차원 배열을 선언 n=int(input("돌의 개수 >> ")) d=[[0 for clo in range(2)] for row in range(n)] #각 돌에는 점수가 적혀있다. for i in range(n): d[i][0]=int(input("돌의 쓰여질 점수 >> ")) #돌을 밟을 때마다 돌에 쓰여진 점수를 누적해서 더해야 되고, #돌의 합이 최대가 되도록 징검다리를 건너고 싶다. score=0 def finish_n(i,d,score): global n #5. 마지막 N번째 돌은 꼭 밟아야 한다. #마지막 돌을 밟으면서 규칙을 어기지 않게 하는 조건 if i==n-3: score+=d[n-1][0] d[n-1][1]=1 print(d) return score elif i==n-2: score+=d[n-1][0] d[n-1][1]=1 print(d) return score else: return 0 def next_stone(i,d,score): finish=finish_n(i,d,score) if finish!=0: return finish #3. 단, 연속된 세 개의 돌을 밟으면 안된다. if d[i][1]==1 and d[i-1][1]==1: score+=d[i+2][0] d[i+2][1]=1 return next_stone(i+2,d,score)#밟는 돌로 넘어가서 다시 실행 #1. 돌은 한번에 하나씩만 밟아야 하며, 작은 번호에서 높은 번호의 순서로 밟아야 한다. #2. i번째 돌을 밟은 상태라면, 다음번에는 i+1번째 돌이나 i+2번째의 돌을 밟을 수 있다. else: if d[i+1][0]>d[i+2][0]: score+=d[i+1][0] d[i+1][1]=1 return next_stone(i+1,d,score)#밟는 돌로 넘어가서 다시 실행 else: score+=d[i+2][0] d[i+2][1]=1 return next_stone(i+2,d,score)#밟는 돌로 넘어가서 다시 실행 #D[i] 배열을 i번째 돌을 밟았을 때의 점수의 최대 누적 값으로 정의할 수 있다. #단, 1,2번 돌에서는 그 최댓값이 무의미할 수 있기 때문에 #(예를 들어 0번:11,1번:29인데 1번을 밟았을 때 가질 수 있는 최댓값은 40이지만 총 최댓값으로 판단했을 경우에는 1번인 29만 밟는 것이 더 큰 결과값을 가질 수 있는 경우) #그 경우를 고려하여 먼저 정리하였다. def first_stone1(dd1): score1=0 i=0 score1+=dd1[0][0]#0번 돌 선택: 0,1 둘다 선택 or 0만 선택 dd1[0][1]=1 #0번 시작의 결과의 최댓값 result1=next_stone(i,dd1,score1) return result1 def first_stone2(dd2): global n for j in range(n): dd2[j][1]=0 score2=0 i=1 score2+=dd2[1][0]#0번 선택 안하고 1번 돌 선택 dd2[1][1]=1 #1번시작의 결과의 최댓값 result2=next_stone(i,dd2,score2) return result2 #0번으로 시작하는 것이 최대인지,1번으로 시작이 최대인지 판별 def max_select(a,b): if a>b: return a else: return b a=first_stone1(d) b=first_stone2(d) score=max_select(a,b) print("돌의 누적 최댓값 : ",score)
# -*- coding: utf-8 -*- """ Created on Mon Aug 27 20:54:12 2018 @author: wyh """ """ Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ rev = 0 a = abs(x) while(a != 0): pop = a % 10 rev = rev * 10 + pop a = a // 10 if x > 0 and rev < 2**31: return rev elif x < 0 and rev <= 2**31: return -rev else: return 0
# -*- coding: utf-8 -*- """ Created on Thu Aug 30 10:37:39 2018 @author: wyh """ """ Given a linked list, remove the n-th node from the end of list and return its head. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ res = ListNode(0)
""" A module for containing any user facing text in the English language.""" from typing import Final APPLICATION_TITLE: Final[str] = "Phonetics Modeling Program" DIALOG_WINDOW_TITLE: Final[str] = "Request" MENU: Final[ str ] = """What do you want to accomplish? 1) view the English phoneme inventory (as IPA graphemes). 2) make a phoneme voiced. 3) make a phoneme unvoiced. 4) describe a phoneme in English. 5) describe a phoneme in SPE Features. 6) divide IPA text into phonemes (chunk) 7) open window (user-friendly mode) Enter the number representing your selection below: after the prompt: and press enter/return.\n\n\n""" USER_INPUT_VIEW_ENGLISH_PHONEME_INVENTORY: Final[str] = "1" USER_INPUT_MAKE_A_PHONEME_VOICED: Final[str] = "2" USER_INPUT_MAKE_A_PHONEME_UNVOICED: Final[str] = "3" USER_INPUT_DESCRIBE_A_PHONEME_IN_ENGLISH: Final[str] = "4" USER_INPUT_DESCRIBE_A_PHONEME_IN_SPE: Final[str] = "5" USER_INPUT_CHUNK_IPA_BY_PHONEME: Final[str] = "6" USER_INPUT_OPEN_WINDOW: Final[str] = "7" PROMPT: Final[str] = "(PROMPT:) " SORRY_UNABLE_TO_CALCULATE: Final[ str ] = "Sorry: unable to calculate answer with that input." PHONEME_TO_DEVOICE_MESSAGE: Final[ str ] = """Type a phoneme using IPA symbols: and then press the enter key: and the computer will display the devoiced counterpart:""" PHONEME_TO_VOICE_MESSAGE: Final[ str ] = """Type a phoneme using IPA symbols: and then press the enter key: and the computer will display the voiced counterpart:""" PHONEME_TO_DESCRIBE_MESSAGE: Final[ str ] = """ Type a phoneme using IPA symbols: and then press the enter key: and the computer will display its English description:""" PHONEME_TO_CALCULATE_SPE_MESSAGE: Final[ str ] = """ Type a phoneme using IPA symbols: and then press the enter key: and the computer will display its SPE features:""" IPA_TEXT_TO_DIVIDE_MESSAGE: Final[ str ] = """ اطبع نص بالرموز ذات الألفباء الصواتية العالمية: ثم اضغط على مفتاح الإدخال: والحاسوب سيريك الوحدات الصواتية من النص كل واحدة على سطر وحدها. Type text using IPA symbols: and then press the enter key: and the computer will display the text you entered with separate phonemes on separate lines:""" PLEASE_READ_README_MESSAGE: Final[ str ] = "Please read README.md file for instructions on how to use." PROGRAM_TERMINATED_NORMALLY_MESSAGE: Final[str] = "Program terminated normally." USER_SELECTED_MESSAGE: Final[str] = "The user selected:" UNRECOGNIZED_SELECTION_MESSAGE: Final[str] = "Unrecognized selection. No action taken." NO_ANALYSIS_FOUND_MESSAGE: Final[str] = "No analysis found!" NO_ENGLISH_DESCRIPTION_FOUND_MESSAGE: Final[str] = "(no English description found.)" CONSONANT_TEXT: Final[str] = "consonant" VOWEL_TEXT: Final[str] = "vowel" FRONT_BACKNESS_TEXT: Final[str] = "front" CENTRAL_BACKNESS_TEXT: Final[str] = "central" BACK_BACKNESS_TEXT: Final[str] = "back" CLOSE_HEIGHT_TEXT: Final[str] = "close" NEAR_CLOSE_HEIGHT_TEXT: Final[str] = "near-close" CLOSE_MID_HEIGHT_TEXT: Final[str] = "close-mid" MID_HEIGHT_TEXT: Final[str] = "mid" OPEN_MID_HEIGHT_TEXT: Final[str] = "open-mid" NEAR_OPEN_HEIGHT_TEXT: Final[str] = "near-open" OPEN_HEIGHT_TEXT: Final[str] = "open" ROUNDED_ROUNDING_TEXT: Final[str] = "rounded" UNROUNDED_ROUNDING_TEXT: Final[str] = "unrounded" BILABIAL_PLACE_TEXT: Final[str] = "bilabial" LABIODENTAL_PLACE_TEXT: Final[str] = "labio-dental" DENTAL_PLACE_TEXT: Final[str] = "dental" ALVEOLAR_PLACE_TEXT: Final[str] = "alveolar" POSTALVEOLAR_PLACE_TEXT: Final[str] = "post-alveolar" RETROFLEX_PLACE_TEXT: Final[str] = "retroflex" PALATAL_PLACE_TEXT: Final[str] = "palatal" VELAR_PLACE_TEXT: Final[str] = "velar" UVULAR_PLACE_TEXT: Final[str] = "uvular" PHARYNGEAL_PLACE_TEXT: Final[str] = "pharyngeal" GLOTTAL_PLACE_TEXT: Final[str] = "glottal" EPIGLOTTAL_PLACE_TEXT: Final[str] = "epiglottal" LABIALVELAR_PLACE_TEXT: Final[str] = "labial-velar" LABIALPALATAL_PLACE_TEXT: Final[str] = "labial-palatal" ALVEOLOPALATAL_PLACE_TEXT: Final[str] = "alveolo-palatal" PALATOALVEOLAR_PLACE_TEXT: Final[str] = "palato-alveolar" PLOSIVE_MANNER_TEXT: Final[str] = "plosive" NASAL_MANNER_TEXT: Final[str] = "nasal" TRILL_MANNER_TEXT: Final[str] = "trill" TAP_OR_FLAP_MANNER_TEXT: Final[str] = "tap or flap" APPROXIMANT_MANNER_TEXT: Final[str] = "approximant" FRICATIVE_MANNER_TEXT: Final[str] = "fricative" AFFRICATE_MANNER_TEXT: Final[str] = "affricate" LATERAL_FRICATIVE_MANNER_TEXT: Final[str] = "lateral fricative" LATERAL_APPROXIMANT_MANNER_TEXT: Final[str] = "lateral approximant" LATERAL_FLAP_MANNER_TEXT: Final[str] = "lateral flap" LATERAL_MANNER_TEXT: Final[str] = "lateral" PULMONIC_EGRESSIVE_AIRSTREAM_TEXT: Final[str] = "pulmonic egressive" CLICK_AIRSTREAM_TEXT: Final[str] = "click" IMPLOSIVE_AIRSTREAM_TEXT: Final[str] = "implosive" VOICED_VOCAL_FOLDS_TEXT: Final[str] = "voiced" VOICELESS_VOCAL_FOLDS_TEXT: Final[str] = "voiceless" VOICED_ASPIRATED_VOCAL_FOLDS_TEXT: Final[str] = "voiced aspirated" VOICELESS_ASPIRATED_VOCAL_FOLDS_TEXT: Final[str] = "voiceless aspirated" CREAKY_VOICED_VOCAL_FOLDS_TEXT: Final[str] = "creaky voiced" SYLLABIC_PHONEME_FEATURE_TEXT: Final[str] = "syllabic" CONSONANTAL_PHONEME_FEATURE_TEXT: Final[str] = "consonantal" SONORANT_PHONEME_FEATURE_TEXT: Final[str] = "sonorant" CONTINUANT_PHONEME_FEATURE_TEXT: Final[str] = "continuant" VOICE_PHONEME_FEATURE_TEXT: Final[str] = "voice" ATR_PHONEME_FEATURE_TEXT: Final[str] = "ATR" NASAL_PHONEME_FEATURE_TEXT: Final[str] = "nasal" LATERAL_PHONEME_FEATURE_TEXT: Final[str] = "lateral" DELAYED_RELEASE_PHONEME_FEATURE_TEXT: Final[str] = "delayed release" SPREAD_GLOTTIS_PHONEME_FEATURE_TEXT: Final[str] = "spread glottis" CONSTRICTED_GLOTTIS_PHONEME_FEATURE_TEXT: Final[str] = "constricted glottis" LABIAL_PHONEME_FEATURE_TEXT: Final[str] = "labial" CORONAL_PHONEME_FEATURE_TEXT: Final[str] = "coronal" DORSAL_PHONEME_FEATURE_TEXT: Final[str] = "dorsal" PHARYNGEAL_PHONEME_FEATURE_TEXT: Final[str] = "pharyngeal" LARYNGEAL_PHONEME_FEATURE_TEXT: Final[str] = "laryngeal" ROUND_PHONEME_FEATURE_TEXT: Final[str] = "round" ANTERIOR_PHONEME_FEATURE_TEXT: Final[str] = "anterior" DISTRIBUTED_PHONEME_FEATURE_TEXT: Final[str] = "distributed" STRIDENT_PHONEME_FEATURE_TEXT: Final[str] = "strident" HIGH_PHONEME_FEATURE_TEXT: Final[str] = "high" LOW_PHONEME_FEATURE_TEXT: Final[str] = "low" BACK_PHONEME_FEATURE_TEXT: Final[str] = "back" SHOW_PHONEME_INVENTORY_TEXT: Final[str] = "Show English phoneme inventory" MAKE_A_PHONEME_VOICED_TEXT: Final[str] = "Make a phoneme voiced…" QUIT_TEXT: Final[str] = "Quit" MAKE_A_PHONEME_UNVOICED_TEXT: Final[str] = "Make a phoneme unvoiced…" DESCRIBE_PHONEME_TEXT: Final[str] = "Describe a phoneme…" GET_FEATURES_OF_PHONEME_TEXT: Final[ str ] = "Get sound patterns of English features of IPA transcription…" SPLIT_TRANSCRIPTION_TEXT: Final[str] = "Split IPA transcription text…" # Headers: RESULT_HEADER: Final[str] = "Result:" VOICED_PHONEME_HEADER: Final[str] = "Voiced Phoneme" UNVOICED_PHONEME_HEADER: Final[str] = "Unvoiced Phoneme" PHONEME_DESCRIPTION_HEADER: Final[str] = "Description of Phoneme" FEATURES_HEADER: Final[str] = "SPE Features of Phoneme" PHONEMES_SPLIT_HEADER: Final[str] = "Phonemes After Being Split" ENGLISH_PHONEME_INVENTORY_HEADER: Final[str] = "English Phoneme Inventory" INPUT_HEADER: Final[str] = "Input:"
import sys import argparse from os import path import json from drawer import draw def main(): if len(sys.argv) < 2: raise Exception("Please provide json file") argparser = argparse.ArgumentParser(description='Parse and draw from json') argparser.add_argument('input', help='path to json') argparser.add_argument('-o', '--output', help='Optional png file to save image') args = argparser.parse_args() # print(args.input) # print(args.output) if not path.isfile(args.input): raise Exception("Input file does not exist") with open(args.input) as input_file: data = json.load(input_file) Figures = data["Figures"] Screen = data["Screen"] Palette = data["Palette"] draw(Figures,Screen,Palette,args.output) if __name__ == "__main__": main()
TAKEN = 1 NOT_TAKEN = 0 class LinearEqn(object): def __init__(self,values,weights,capacity): """values and weights : list of ints capacity :an int """ self.values = values self.weights = weights self.capacity = capacity self.recursion = 0 self.solution = [] #don't know how 2 find d items which were put aprt frm another exhaustive serach def exhaust(self,sampleSpace , capacity): """ sampleSpace : a list [0,1,2] denotes dat dere r 3 items [1,2] denotes dat dere r 2 objects remaining, 2 b particular 2nd and 3rd capacity : int denotes how much more weigty can b put in d bag """ if capacity <= 0 or not sampleSpace: return 0 print sampleSpace , "\t" , capacity item = sampleSpace.pop(0) self.recursion += 1 if capacity - self.weights[item] >= 0: taken = self.values[item] + self.exhaust(sampleSpace[:] , capacity - self.weights[item]) else: return self.exhaust(sampleSpace[:] , capacity) not_taken = self.exhaust(sampleSpace[:] , capacity) ans = max(taken , not_taken) return ans values = [45,48,35] weights = [5,8,2] capacity = 10 l = LinearEqn(values,weights , capacity) print l.exhaust([0,1,2] , capacity ) print l.recursion
def add(param1, param2): result = param1 + param2 return result def multiply(param1, param2): result = param1 * param2 return result if __name__ == "__main__": # function call print(add(5, 10)) print(multiply(5, 10))
myName = input("your name: ") myAge = int(input("your age: ")) print("1. Hello World, my name is %s and I am %d years old." % (myName, myAge)) print("2. Hello World, my name is %s and I am %s years old." % (myName, myAge)) print("3. Hello World, my name is {} and I am {} years old.".format(myName, myAge)) print('4. Hello World, my name is {0:s} and I am {1:d} years old.'.format(myName, myAge)) print("5. Hello World, my name is " + myName + " and I am " + str(myAge) + " years old.") print("6. Hello World, my name is " + myName + " and I am", myAge, "years old.") ''' Summary 1. int value can be output as %d or %s 2. raw_input() accepts input as string. (Python 2) 3. print(), brackets can be ignored in Python 2 '''
import numpy as np def skosnosc(x): n=len(x) srednia=np.mean(x) skos=[] for i in range(n): skos.append(float((x[i]-srednia)**3)) print('skosnosc wynosi ' + str(sum(skos)/n)) lista=[5.5,5.8,14.12,28.3,25.5,3.9,1.1] skosnosc(lista)
from hangman.game import Hangman """ Hangman Runner @Author Afaq Anwar @Version 02/21/2019 """ current_game = Hangman() print("Welcome to Hangman!" + "\n" + "Attempt to guess the word!") current_game.update_display() while not current_game.game_over: current_game.guess(input("Type...")) current_game.update_display()
# -*- coding: utf-8 -*- """ Created on Sun Oct 1 12:30:35 2017 @author: smvaz """ #improting requeired lib import math def POISSON(Lambda, y): #define a function to calculate poisson dist pmf= math.exp(-Lambda) * Lambda**y / math.factorial(y) return pmf # a for loop for calculation of 4=<y=<9 Lambda=3 pmf=0 for y in range(4,10): pmf=POISSON(Lambda,y)+pmf print('pmf for 4=<y=<9 and Lambda=%s is %s' %(Lambda, pmf)) print('pmf for 9<y or y<4 and Lambda=%s is %s' %(Lambda, 1-pmf))
# JSON is commonly used with data API's. Here how we can parse JSON into a Python Dictionary import json # Sample JSON userJSON = '{"first_name": "Nandy", "last_name": "Mandy", "age": 23}' # Parse to dictionary user = json.loads(userJSON) print(user) # dictionary to JSON car = {'make': 'Aston', 'model': 'Martin', 'year': 1990} carJSON = json.dumps(car) print(carJSON)
print("Welcome to Good Burger") total=0 #iteration 1 sandwich=input("What kind of sandwich do you want, chicken for $5.25 (c), beef for $6.25 (b), or tofu for $5.75 (t)? ") print(sandwich) if sandwich=="c": total+=5.25 elif sandwich=="b": total+=6.25 elif sandwich=="t": total+=5.75 #iteration 2 beverage=input("Would you like a beverage, y or n? ") if beverage=="y": beverage=input("Small for $1.00 (s), medium for $1.75 (m), large for $2.25 (l), or child for $2.63 (c)? ") print("You said",beverage) #print(string,string,string) else: print("no") if beverage=="s": total+=1 elif beverage=="m": total+=1.75 elif beverage=="l": total+=2.25 elif beverage=="c": total+=2.63 #iteration 3 fries=input("Would you like fries, y or n? ") if fries=="y": fries=input("Small for $1.00 (s), medium for $1.50 (m), or large for $2.00 (l)? ") print("You said",fries) else: print("no") if fries=="s": total+=1 elif fries=="m": total+=1.5 elif fries=="l": fries=input("Would you like a child size fry instead for an additional $0.38, y or n? ") if fries=="y": #nested conditional statement total+=2.38 else: total+=2 #print("Your total is $",total) print("${:,.2f}".format(total)) #string formation
#!/usr/bin/python3 from string import ascii_lowercase lines = [] with open("input.txt") as filehandler: for line in filehandler: lines.append(line[:len(line) - 1]) # PART ONE count_two_of_any_letter = 0 count_three_of_any_letter = 0 for line in lines: found_exactly_two = False found_exactly_three = False letter_frequencies = {} for letter in ascii_lowercase: # Initialize all letters with 0 letter_frequencies[letter] = 0 for letter in line: # Count actual letters letter_frequencies[letter] += 1 # print(letter_frequencies) for letter in letter_frequencies: # Search for exactly two or three if letter_frequencies[letter] == 2: found_exactly_two = True if letter_frequencies[letter] == 3: found_exactly_three = True if found_exactly_two: count_two_of_any_letter += 1 if found_exactly_three: count_three_of_any_letter += 1 print("Count two: {}\nCount three: {}\n{} * {} = {}".format(count_two_of_any_letter, count_three_of_any_letter, count_two_of_any_letter, count_three_of_any_letter, count_two_of_any_letter * count_three_of_any_letter)) # PART TWO for index, line in enumerate(lines): for compare_line in lines[index + 1:]: found_one_different_char = False differ_pos = None for char_index, char in enumerate(line): if char != compare_line[char_index]: if not found_one_different_char: found_one_different_char = True differ_pos = char_index else: # Found a second char that differs found_one_different_char = False break if found_one_different_char: print("Line \"{}\" and \"{}\" differ only by one letter at the same position. The common letters are {}.".format(line, compare_line, line[:differ_pos] + line[differ_pos + 1:]))
""" K-Nearest Neighbours -> Is a classification algorithm wich classify cases based on their similarity to other cases; -> Cases that are near each other are said to be neighbors; -> Similar cases with same class labels are near each other. How it really works? 1. Pick a value for K; 2. Calculate the distance of unkown case from all cases; 3. Select de K-Observations in the training data that are "nearest" to the unknown data point; 4. Predict the response of the unknown data point using the most popular (moda) resopnse value from the K-nearest neighbors. 2. How we can calculate the distance? -> Distância euclidianada: Distância vetorial, ou seja, Pitágoras. 1. What de best valures of de K for KNN? -> Se o K for muito pequeno, podemos nos deparar uma anomalia nos dados, o que nos da uma péssima acurácia . Além disso, temos um problema de overfiting, servindo apenas para os dados utilizados e não para um caso diferente; -> Se o K for muito grande, o modelo se torna overgeneralized. -> Ou seja, para saber qual o melhor, é necessário ir testando. """
#import pymongo import pymongo from pymongo import * #connect python to mongo client = MongoClient() #connect to a new or existing Data Base Data_Base = client.database #Data_Base is the name python will use to refer to the database #DB is the name of the database in mongo(or the oone that will e created) #Then connect t a collection in the data base User = Data_Base.collection # User is the name python uses and collection is the name of the collection in mongo #My approach was to first create a document with available info then later edit that document # To create a document create a dictionary then insert into mongo using a .insert() function profile = {"Name" : "Eric"} # This is where you use the .get() for the value of the keys # eg. age = age_entry.get() ...so this has to be in a funtion that comes after actually getting the data from the entrys #Then add it to mongo User.insert_one(profile) # Now you can edit the document using a special feature like name as a query # If your using same script just use the .update_one() which first takes the query dictionary , then the updated one and the word $set User.update_one({"Name" : "Eric"} , {"$set" :{"BMI" : "323"}}) #The name and bmi should be replaced with the name of the varriables you have for them # Or you could create a list of documents in the collection then arrange them in descending order # Set a limit to only find one which will be the last created document List = list(User.find({},sort = [( '_id', pymongo.DESCENDING )]).limit(1)) #print List to see the format ..currently idk what that means so.. data = dict(List[0]) # this makes it a dictionary of the first item that we can with # get the info you need to make a query id = data["_id"] # can be anything else # Then you can edit it User.update_one({"_id" : id}, {"$set" : {"BMI" : "40"}})
from threading import Thread,Condition from time import sleep # notify(n=1)--> this method is used to immediately wake up one thread waiting on the condition.where n is number of thread need to wake up (by default value is 1) # notify_all()--> this metohd is used to wake up all threads waiting on the condition # wait(Timeout=None)-->This method wait until notified or until a timeout occurs lst=[] def produce(): cv.acquire() for i in range(1,6): lst.append(i) sleep(0.5) print("Item Produced...") cv.notify() cv.release() def consume(): cv.acquire() cv.wait(timeout=0) cv.release() print(lst) cv=Condition() t1=Thread(target=produce) t2=Thread(target=consume) t1.start() t2.start()
################# #Tyler Robbins # #1/19/14 # #FTPConnect # ################# import sys, os from ftplib import FTP from getpass import getpass import platform if platform.system() == 'Windows': slash = "\\" else: slash = "//" while True: ulogin = True url = raw_input(">>> FTP server (example.com) or (ip.ip.ip:anIP): ") #gets website/server from user try: ftp = FTP("ftp." + url) #Allows the user to choose what server to connect to break except Exception as e: if str(e) == '[Errno 11001] getaddrinfo failed': print "Could not find '" + str(url) + "'." else: print str(e) while ulogin: user = raw_input(">>> UserName: ") #gets username if user == "!q": print "Closing connection." ftp.quit() sys.exit() passw = getpass(">>> Password: ") #gets password if passw == "!q": print "Closing connection." ftp.quit() sys.exit() try: ftp.login(user, passw) #tries to input username and password ulogin = False except Exception as e: #catches login error if str(e) == '530 Login incorrect.': print ">>> Incorrect login." else: print ">>> " + str(e) i=0 i+=1 if i >= 5: print ">>> Incorrect " + i + " times. Closing connection." ftp.quit() sys.exit() print "Permissions", " Last Updated", "Files/Folders" ftp.retrlines('LIST') #list all directories while True: choice = raw_input('>>> ') #user lists commands try: if choice.lower() == 'exit': #exits program try: ftp.quit() exit() except EOFError: print "Connection timed out" elif choice.lower() == 'help': #prints help for the user print """cd [destination] upload [location] [name] download [name] rm [name] ren [name] exit help ls {directory} mkdir [name] rmdir [name] chdir """ elif choice.split(" ")[0] == 'cd': cd = choice.split(" ", 1) cd.remove("cd") try: if slash in cd: cd = cd.split(slash) for item in cd: ftp.cwd(item) #changes to directory of choice except Exception as e: if str(e) == 'FileNotFoundError': print ">>> Could not find '" + choice.split(" ")[1] + "'. Destination does not exist." else: print str(e) elif choice.split(" ")[0] == 'ls': #lists directories and files try: loc = ftp.pwd() if " " in choice: choice = choice.split(" ", 1) choice = choice.split(" ", 1).split("/") for item in choice: ftp.cwd(item) #allows the user to list in a separate directory print "Permissions", " Last Updated", "Files" ftp.retrlines('LIST') ftp.cwd(loc) except(Exception): print ">>> Could not find '" + choice.split(" ")[1] + "'. Destination does not exist." elif choice.split(" ")[0] == 'rm': #remove file ask_user = getpass(">>> Server password: ") try: if ask_user == user: ftp.delete(choice.split(" ")[1]) else: print ">>> Permission denied. Incorrect Login." except Exception: print ">>> Error. Could not find " + choice.split(" ")[1] + "." elif choice.split(" ")[0] == 'ren': #rename file name = raw_input(">>> Rename " + choice.split(" ")[1] + " to: ") #get new name try: ftp.rename(choice.split(" ")[1], name) except Exception: print ">>> Could not find " + choice.split(" ")[1] + "." elif choice.split(" ")[0] == 'read': #read file name = choice.split(" ", 1)[1] extension = choice.split(" ", 1)[1].split(".")[1] #get file extension try: i = '' if "temp" in os.getcwd(): #stops temp dir from overwriting existing temp dirs for item in os.getcwd(): if item == "temp": i += 1 while True: try: os.mkdir("temp" + str(i)) #make temp directory os.chdir("temp") break except OSError as e: print e try: loc = ftp.pwd() choice = choice.split(" ", 1) choice = choice.split(" ", 1).split("/") for item in choice: ftp.cwd(item) except Exception: print ">>> Could not find '" + choice.split(" ")[1] + "'. Destination does not exist." x = open("temp." + extension, 'wb') #make tempfile ftp.retrbinary('RETR ' + choice.split(" ", 1)[1], x.write) #write to tempfile ftp.sendcmd('TYPE i') x.close() x = open("temp." + extension, 'rb') #read tempfile print x.read(), raw_input("> Press any key to continue: ") x.close() except Exception as e: print "error" print str(e) os.remove("temp." + extension) #remove tempfile and folder os.chdir("..") os.rmdir("temp") ftp.cwd(loc) elif choice.split(" ")[0] == 'mkdir': #makes directory choice = choice.split(" ") try: ftp.mkd(choice[1]) #create specified directory except(Exception): print ">>> Destination already exists." elif choice.split(" ")[0] == 'rmdir': #removes directory ask = raw_input(">>> Warning! This action cannot be undone. Do you wish to continue?(y/n) ") #ask user for confirmation to continue if ask == 'y': try: ftp.rmd(choice.split(" ")[1]) #remove specified directory except(Exception): print ">>> Could not remove '" + choice.split(" ")[1] + "'. Destination does not exist." elif choice.split(" ")[0] == 'upload': #copies file loc = choice.split(" ")[1] name = loc.split(slash)[len(loc.split(slash)) - 1] #uploads file with same name as the original try: upload = open(loc, 'rb') #opens file ftp.storbinary('STOR ' + name, upload) #sends file upload.close() #closes file except(Exception): print ">>> Could not find '" + name + ".' in '" + loc + "'." elif choice.split(" ")[0] == 'download': choice = choice.split(" ", 1) try: print "Current working directory: " + str(os.getcwd()) print "Type 'currdir' to use the current directory." loc = raw_input("Type the destination path for where you want to save " + choice[1] + ": ") #get save location from the user if loc == 'currdir': loc = os.getcwd() x = open(loc + slash + choice[1], 'wb') #open file for writing ftp.retrbinary('RETR ' + choice[1], x.write) ftp.sendcmd("TYPE i") x.close() except Exception as e: print e print ">>> Error. File " + choice[1] + " not found." elif choice == 'currdir': print ">>> Current os directory: ", print str(os.getcwd()) elif choice == 'chdir': print ">>> Current working directory:", print str(os.getcwd()) loc = raw_input(">>> Change directory to: ") os.chdir(loc) elif choice[:2] == "./": ftp.retrbinary('RETR ' + choice.split(choice[:2])) else: print ">>> '" + choice + "': Command not found." if choice == '`': sys.exit() except Exception as e: #catches errors that make it past other error handlers if str(e) == "[Errno 10053] An established connection was aborted by your host machine": ftp.quit() sys.exit() elif str(e) == "421 No transfer timeout (600 seconds): closing control connection": print "No file transfer for 600 seconds. Connection timed out." ftp.quit() sys.exit() else: print ">>> " + str(e) nuclear = u'\u2622'
usrinput=int(raw_input()) if usrinput<0: print "Negative" elif usrinput>0: print "Positive" elif usrinput==0: print "Zero"
def hcf1(x1,x2): while(x2!=0): t=x2 x2=x1%n2 x1=t return x1 def main(): m=int(input()) q=int(input()) (l,r)=([],[]) for i in range(m): l.append(int(input())) print(l) for c in range(q): x1=int(input()) x2=int(input()) r.append(hcf1(l[x1-1],l[x2-1])) for i in r: print(r) try: main() except: print('invalid')
def triplets(tot,l): n=len(l) for i in range(n-2): for j in range(i+1,n-1): for k in range(j+1,n): if l[i]+l[j]+l[k]==tot: return l[i],l[j],l[k] return 'none' def main(): n=int(input()) l=[] for i in range(n): l.append(int(input())) tot=int(input()) print(triplets(tot,l)) try: main() except: print('invalid')
print('''you the scared night guard in an abandoned mansion in the middle of a forest, you see a ghost down the hall. What do you do?''') print('do you turn left and go into the closet, or do you turn right and jump out the window?') turn = input(' type left or right: ') if turn == 'left': print('you enter the closet and you find a flash light and a dead battery') turn2 = input() if turn2 == "": print() else: print() #you need to find batterys. elif turn == 'right': print('you just jumped out the window and landed in a dumpster that is too dark to see, but found a knife') #what do you use the knife for. else: quit print(
#!/usr/bin/env python import pprint pp = pprint.PrettyPrinter(indent=4) class Carta (): x=4 def __init__(self, palo=0, valor=0): self.palo = palo self.valor = valor def __str__(self): #return("aqui hay que devolver self.palo y self.valor") return("("+str(self.valor)+" "+self.palo+") ") class Mazo: #~ def EligePalo(): def __init__(self): numeros = [1,2,3,4,5,6,7,10,11,12] palos = ['Bastos','Oros','Diamantes','Copas'] self.cartas = [] for palo in palos: for valor in numeros: self.cartas.append(Carta(palo, valor)) #~ def muestraMazo(self): #~ def muestraMazo(self): #~ for carta in self.cartas: #~ print carta.valor," ",carta.palo def mezclar(self): import random nCartas = len(self.cartas) for i in range(nCartas): j = random.randrange(i, nCartas) self.cartas[i], self.cartas[j] = self.cartas[j], self.cartas[i] def darCarta(self): return self.cartas.pop()
''' Blockchain, Module 1 Created by: Isaac Harasty This python module is what is accomplished in the 'Module 1' Section of the slides that were submitted for this project. Creates a cryptographically linked chain of blocks with basic data fields, including Time Stamps, Block Index, the Previous Hash, and Nonce for mining. Also, uses flasks to create endpoints capable of a few basic operations, namely getting the chain, and mining a new block. ''' import datetime import json import hashlib from flask import Flask, jsonify # Creating the BlockChain class BlockChain: ''' The block chain object. Capable of functionality outlined above, a cryptographically linked list of 'blocks'. In this module, blocks have yet to hold transactions, but are rather dict() objects of the following structure. { 'index': int, 'timestamp': str, 'nonce': int, 'previous_hash': str } Attributes: --------------- chain: List The effectual block chain, a Python list object full of Block dicts ''' def __init__(self): self.chain = [] genesis_block = self.find_new_block('0') self.chain.append(genesis_block) def add_block(self, block): ''' Adds a block to the chain. Assumed that blocks are of the correct form. :param block: a dict object representing a block :return: the block that was added/inputted ''' self.chain.append(block) return block def get_prev_block(self): ''' Returns the last block of the block chain :return: dict object representing the most recent (last) block added ''' return self.chain[-1] def hash(self, block): ''' A method of the block chain to find the Hash of an inputted block. Uses the hashlib's SHA256 method to return the hexdigest() :param block: A block dictionary :return: a String representation of the block's hash ''' encoded_block = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(encoded_block).hexdigest() def find_new_block(self, previous_hash): ''' Proof of Work algorithm. Difficulty is currently set to 4 by functionality. Creates a prospective new block to be added to the chain with the hash of the prev block inputted. Continue to increment the Nonce value until you get a hash that satisfies the POW requierment of 4 leading 0's :param previous_hash: String representation of the last blocks SHA256 Hash :return: the new block Dict() object. ''' new_nonce = 1 check_nonce = False new_block = { 'index': len(self.chain) + 1, 'timestamp':str(datetime.datetime.now()), 'nonce': new_nonce, 'previous_hash':previous_hash } while not check_nonce: hash_operation = self.hash(new_block) if hash_operation[:4] == '0000': check_nonce = True else: new_nonce += 1 new_block['nonce'] = new_nonce return new_block # checking the critical features of the block chain def is_chain_valid(self,chain): ''' method to check if a given chain is crytographically valid. This means the following 2 conditions are met. 1) make to make sure each nonce of work is correct 2) each hash of the previous block is the correct hash :param chain: a List object representing the block chain being checked. Each item in chain must be a dictionary following the system above. :return: True if it is valid, False if not ''' previous_block = chain[0] block_index = 1 while block_index < len(chain): block = chain[block_index] if block['previous_hash'] != self.hash(previous_block): return False previous_nonce = previous_block['nonce'] nonce = block['nonce'] hash_operation = hashlib.sha256(str(nonce ** 2 - previous_nonce ** 2).encode()).hexdigest() if hash_operation[:4] != '0000': return False previous_block = block block_index += 1 return True # Creating the Web App app = Flask(__name__) block_chain = BlockChain() @app.route('/mine_block', methods = ['GET']) def mine_block(): previous_block = block_chain.get_prev_block() previous_hash = block_chain.hash(previous_block) block = block_chain.find_new_block(previous_hash) block_chain.add_block(block) return jsonify(block), 200 @app.route('/get_chain', methods = ['GET']) def get_chain(): response = {'chain': block_chain.chain, 'length': len(block_chain.chain)} return jsonify(response), 200 # Running the app if __name__ == '__main__': app.run( host = '0.0.0.0', port=5000 )
import unittest from temptracker import TempTracker, InvalidTemperatureError, TempTrackerError class TestTempTracker(unittest.TestCase): """Test critical functionality for `TempTracker`. To keep things simple, specific sample test-values can be included below as class variables. """ _sample_nested_list = [2, [68, 70, [[110]]], 98, 109, [5, [101, 102]]] _sample_min = 2 _sample_max = 110 def test_can_instantiate_with_no_args(self): tt = TempTracker() self.assertIsInstance(tt, TempTracker) def test_can_instantiate_with_initial_list(self): val = [68] tt = TempTracker(val) self.assertIsInstance(tt, TempTracker) and self.assertEqual(tt[0], val) def test_cannot_instantiate_with_invalid_arg(self): invalid_val = "98.44" with self.assertRaises(TempTrackerError) as err: TempTracker(invalid_val) def test_cannot_insert_invalid_temperature(self): invalid_val = 98.44 tt = TempTracker() with self.assertRaises(InvalidTemperatureError) as err: tt.insert(invalid_val) def test_get_max(self): tt = TempTracker(self._sample_nested_list) self.assertEqual(tt.get_max(), self._sample_max) def test_get_min(self): tt = TempTracker(self._sample_nested_list) self.assertEqual(tt.get_min(), self._sample_min) def test_get_mean(self): tt = TempTracker(self._sample_nested_list) self.assertIsInstance(tt.get_mean(), float) if __name__ == '__main__': unittest.main()
""" Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] self.level = {} def inorder(root, level): if root: if level in self.level: self.level[level].append(root.val) else: self.level[level] = [root.val] inorder(root.left, level + 1) inorder(root.right, level + 1) inorder(root, 0) l = [self.level[key] for key in range(max(self.level)+1)] return l
""" Two Sum II - Input array is sorted - https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 """ class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ # meet in the middle algorithm l = 0 r = len(numbers) - 1 while l < r: total = numbers[l] + numbers[r] # numbers found if total == target: return [l+1, r+1] # if the sum of numbers is less than target, increase l by 1 elif total < target: l += 1 # sum of numbers is greater than target, decrease r by 1 else: r -= 1 # a = Solution() # print(a.twoSum([2,7,11,19], 9))
""" Implementation of a dynamic array in python """ import unittest import random class Array: def __init__(self): self._capacity = 5 self._size = 0 self._array = [None for i in range(5)] def size(self): return self._size def capacity(self): return self._capacity def is_empty(self): """ Return True if Array is empty, False otherwise """ if self._size == 0: return True return False def at(self, index): """ Return the item at the given index """ assert index < self._size and index >= 0 return self._array[index] def push(self, item): """ Add the given item at the end of array """ self.resize() if self._size < self._capacity: self._array[self._size] = item self._size += 1 return True return False def insert(self, index, item): """ Insert item at index, shifts that index's value and trailing elements to the right. """ assert index <= self._size self.resize() if self._size < self._capacity: self._size += 1 self.resize() for i in range(self._size, index, -1): self._array[i] = self._array[i-1] self._array[index] = item return True return False def prepend(self, item): """ Insert item at the start of the array """ return self.insert(0, item) def pop(self): """ Remove an item from the end of array and returns it """ self.resize() if self._size > 0: item = self._array[self._size-1] self._size -= 1 return item return False def delete(self, index): """ Delete item at index, shifting all trailing elements left """ assert index < self._size self.resize() if self._size > 0: item = self._array[index] for i in range(index, self._size): self._array[i] = self._array[i+1] self._size -= 1 return True return False def find(self, item): """ Looks for value and returns first index with that value, -1 otherwise """ for i in range(self._size): if self._array[i] == item: return i return -1 def remove(self, item): """ Looks for value and removes index holding it, even in multiple places """ if self._size == 0: return False self.resize() i = 0 while True: if i >= self._size: break if self._array[i] == item: self.delete(i) else: i += 1 return True def resize(self): """ When array is full, doubles the capacity of the array When size of array is 1/4 of capacity, resize to half """ if self._size == 0: self._capacity = 5 self._array = [None for i in range(5)] elif self._size == self._capacity: # new capacity for the array new_capacity = int(self._capacity * 1.5) + 1 new_array = [None for i in range(new_capacity)] # copy all the elements from the original array to resized array for i in range(self._size): new_array[i] = self._array[i] self._array = new_array self._capacity = new_capacity # if size is 1/4 of the capacity elif self._size <= int((1//4) * self._capacity): new_capacity = self._capacity // 2 new_array = [None for i in range(new_capacity)] for i in range(self._size): new_array[i] = self._array[i] print("Half: ", new_array) self._array = new_array self._capacity =new_capacity else: return True class TestArray(unittest.TestCase): """ Test cases for Array class """ def test_array(self): arr = Array() assert arr.pop() == False assert arr.is_empty() == True assert arr.size() == 0 assert arr.find(200) == -1 for i in range(10): assert arr.push(i) == True assert arr.find(5) == 5 assert arr.at(9) == 9 assert arr.size() == 10 for i in range(9, -1, -1): assert arr.pop() == i assert arr.find(8) == -1 assert arr.size() == 0 for i in range(100, 200): assert arr.prepend(i) == True assert arr.at(50) == 149 assert arr.at(99) == 100 assert arr.size() == 100 for i in range(99, -1, -1): assert arr.delete(i) == True assert arr.size() == 0 for i in range(5000, 6000): assert arr.insert(0, i) == True assert arr.size() == 1000 assert arr.find(5500) == 499 assert arr.find(5000) == 999 assert arr.find(5999) == 0 assert arr.at(200) == 5799 for i in range(5000, 6000): assert arr.remove(i) == True assert arr.size() == 0 def test_using_python_list(self): arr = Array() lst = [] # Enter 1000 numbers in the list and array for i in range(1000): arr.push(i) lst.append(i) assert arr.size() == len(lst) # check for equality for i in range(1000): assert arr.at(i) == lst[i] # Check pop() for i in range(1000): assert arr.pop() == lst.pop() assert arr.size() == len(lst) for i in range(10000): arr.push(i) lst.append(i) assert arr.size() == len(lst) for i in range(60000, 60030): arr.insert(500, i) lst.insert(500, i) for i in range(10030): assert arr.at(i) == lst[i] # Delete from an index for i in range(500, 700): arr.delete(i) lst.pop(i) for i in range(9830): assert arr.at(i) == lst[i] for i in range(100, 400): assert arr.find(i) == lst.index(i) if __name__ == '__main__': unittest.main()
""" Prefix Sum Array """ """ Example of a prefix sum Array - geeksforgeeks.org Input : arr[] = {10, 20, 10, 5, 15} Output : prefixSum[] = {10, 30, 40, 45, 60} Explanation : While traversing the array, update the element by adding it with its previous element. prefixSum[0] = 10, prefixSum[1] = prefixSum[0] + arr[1] = 30, prefixSum[2] = prefixSum[1] + arr[2] = 40 and so on. """ def prefix_sum_array(array): """ Takes an array of integers and returns its prefix sum array """ prefix_arr = [None] * len(array) sofar = array[0] prefix_arr[0] = array[0] for i in range(1, len(array)): sofar += array[i] prefix_arr[i] = sofar return prefix_arr a = [10, 20, 10, 15, 30] print(prefix_sum_array(a))
""" Frievald's algorithm to chech matrix multiplication """ import random def mat_mul(A, B, n): """ A, B are two n*n square matrices Returns matrix C as the product of A and B """ C = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): for k in range(n): C[i][j] += A[i][k] * B[k][j] return C A = [[2,3], [3,4]] B = [[1,0], [1,2]] n = 2 #C = [[6,5], [8,7]] def mul_column_vector(A, B, C, r, n): """ outputs A.(B.r) and (C.r) """ b = [[0] for i in range(n)] a = [[0] for i in range(n)] c = [[0] for i in range(n)] # calculates (B.r) and (C.r) for i in range(n): for k in range(n): b[i][0] += B[i][k] * r[k][0] c[i][0] += C[i][k] * r[k][0] # Calculates A.(B.r) for i in range(n): for k in range(n): a[i][0] += A[i][k] * b[k][0] b = [[0] for j in range(n)] # Calculates A.(B.r) - (C.r) for i in range(n): b[i][0] = a[i][0] - c[i][0] for i in range(n): if b[i][0] != 0: return False return True def frievald(A, B, C, n): """ Check whether product of two square matrices A and B is correct or not. """ # Generate a random column vector true = 0 for i in range(10): r = [[random.randint(0,1)] for j in range(n)] print(r) if mul_column_vector(A, B, C, r, n) is True: true += 1 if true == 10: print("Probability of error = 0") else: print("Probability of error: ", 1/2**10) #print("Correct with probability = %f", (true/30)) def main(A, B, n): """ Calculates matrix C as A x B and checks whether the multiplication is correct """ C = mat_mul(A, B, n) frievald(A, B, C, n)
""" Valid Palindrome - https://leetcode.com/problems/valid-palindrome/ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. """ class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s = s.lower() a = [s[i] for i in range(len(s)) if (97 <= ord(s[i]) <= 122) or (48 <= ord(s[i]) <= 57)] return a == a[::-1] a = Solution() print(a.isPalindrome("A man, a plan, a canal: Panama"))
""" Next Closest Time - https://leetcode.com/problems/next-closest-time/description/ Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. Example 1: Input: "19:34" Output: "19:39" Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. Example 2: Input: "23:59" Output: "22:22" Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically. """ class Solution(object): def nextClosestTime(self, time): """ :type time: str :rtype: str """ hour = int(time[:2]) minutes = int(time[3:]) nums = [int(time[0]), int(time[1]), int(time[3]), int(time[4])] nums.sort() can = False n = None for i in nums: if i > int(time[-1]): can = True n = i break if can is True: return time[:-1] + str(n) for i in nums: if i > int(time[-2]) and int(str(i) + str(nums[0])) <= 59: can = True n = i break if can is True: return time[:-2] + str(n) + str(nums[0]) for i in nums: if i > int(time[1]) and int(time[0] + str(i)) < 24: can = True n = i break if can is True: return time[0] + str(n) + ":" + str(nums[0])*2 for i in nums: if i > int(time[0]) and int(str(i) + str(nums[0])) < 24: can = True n = i break if can is True: return str(n) + str(nums[0]) + ":" + str(nums[0]) + str(nums[0]) return str(nums[0])*2 + ":" + str(nums[0])*2 a = Solution() print(a.nextClosestTime("16:25"))
""" Convert BST to Greater Tree - https://leetcode.com/problems/convert-bst-to-greater-tree Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return("Value: " + str(self.val)) def __str__(self): return("Value: " + str(self.val)) class Solution(object): def convertBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ self.sofar = 0 def inorder(root): if root: inorder(root.right) root.val += self.sofar self.sofar = root.val inorder(root.left) inorder(root) # a = Solution() # t1 = TreeNode(5) # t2 = TreeNode(2) # t3 = TreeNode(13) # t1.left = t2 # t1.right = t3 # print(a.convertBST(t1))
""" https://www.hackerearth.com/codathon-nitbhopal/algorithm/new-government-new-name/ """ import string def type1(query, strg, str_dict): pos = int(query[1]) - 1 char = query[2] # Replacing in strg and updating values in dictionary str_dict[strg[pos]] -= 1 strg[pos] = char str_dict[char] += 1 def type2(query, strg, str_dict): pos = int(query[1]) count = 1 for char in string.ascii_uppercase: if count + str_dict[char] > pos: print(char) return else: count += str_dict[char] def main(): string_size, num_queries = input().split() string_size = int(string_size) num_queries = int(num_queries) strg = list(input()) # initializing dictionary str_dict = {} for c in string.ascii_uppercase: str_dict[c] = 0 # updating the number of occurrences of characters for char in strg: str_dict[char] += 1 # getting queries queries = [] for i in range(num_queries): queries.append(input().split()) for query in queries: if query[0] == '1': type1(query, strg, str_dict) else: type2(query, strg, str_dict)
""" Repeated Substring Pattern Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the substring "ab" twice. Example 2: Input: "aba" Output: False Example 3: Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) """ class Solution(object): def repeatedSubstringPattern(self, s): """ :type s: str :rtype: bool Insights: - the first char of s equals first char of repeated substring. - the last char of s equals last char of repeated substring. - if s has a repeated substring pattern, then that substring occurs at least 2 times. Hence (s + s)[1:-1] must include s if s is made up of a repeated substring. Eg: s = "abab" first char = "a", last char = "b" s + s = "abababab" (s + s)[1:-1] = "bababa" contains s (index 1-4) """ return (s+s)[1:-1].find(s) != -1
""" Implementation of a Binary Tree """ class Node(object): """ A node contains some information """ def __init__(self, value): self.value = value self.parent = None self.left = None self.right = None def inorder(root): """ Prints the inorder traversal of a tree """ if root != None: inorder(root.left) print(root.value, end=" ") inorder(root.right) def preorder(root): """ Prints the preorder traversal of a tree """ if root != None: print(root.value, end=" ") preorder(root.left) preorder(root.right) def postorder(root): """ Prints the postorder traversal of a tree """ if root != None: postorder(root.left) postorder(root.right) print(root.value, end=" ") class BinarySearchTree(object): """ Binary search tree is a binary tree in which each node > left child and <= right child """ def __init__(self): self.root = None self.length = 0 def length(self): return self._length def TreeSearch(x, key): """ Search the given node in a Binary Search Tree """ if x is None or key == x.value: return x elif x.value < key: return TreeSearch(x.right, key) else: return TreeSearch(x.left, key) def TreeMinimum(x): """ Finds the minimum element in a binary search tree """ while x.left is not None: x = x.left return x def TreeMaximum(x): """ Finds the maximum element in a binary search tree """ while x.right is not None: x = x.right return x def TreeSuccessor(x): """ Finds the successor of x in a binary Search Tree """ if x.right is not None: return TreeMinimum(x) y = x.parent while (y is not None and x == y.right): x = y y = y.parent return y def TreePredecessor(x): """ Find the predecessor of x in a binary search tree """ if x.left is not None: return TreeMaximum(x) y = x.parent while (y is not None and x == y.right): x = y y = y.parent return y def TreeInsert(T, z): """ Inserts node x in a binary search tree T """ y = None x = T.root # find the right position to insert node z while x is not None: y = x if z.value < x.value: x = x.left else: x = x.right # insert node z in BST T z.parent = y if y is None: T.root = z # tree is empty elif z.value < y.value: y.left = z else: y.right = z def Transplant(T, u, v): """ Replaces node v with node u """ if u.parent is None: T.root = v elif u == u.parent.left: # if u is left node of its parent u.parent.left = v else: u.parent.right = v if v is not None: v.parent = u.parent def TreeDelete(T, z): """ Deletes a node z from a BST T """ # if left subtree of z is empty replace z with its right child if z.left is None: Transplant(T, z, z.right) # if right subtree of z is empty replace z with its left child elif z.right is None: Transplant(T, z, z.left) else: # find the successor y = TreeMinimum(z.right) # if its not the right child of z if y.parent != z: # replace y with its right child, y has no left child being successor Transplant(T, y, y.right) # connect y with the right subtree z y.right = z.right y.right.parent = y # replace z with y Transplant(T, z, y) # connect y with the left subtree of z y.left = z.left y.left.parent = y def lowest_common_ancestor(x, y): """ Find the lowest common ancestor of x and y in a tree """ p1 = [x] # contains parents of x including x p2 = [y] # contains parents of y including y node1, node2 = x, y # find all the ancestors of x while node1.parent is not None: p1.append(node1.parent) node1 = node1.parent # find all the ancestors of y while node2.parent is not None: p2.append(node2.parent) node2 = node2.parent LCA = None while p1 and p2: # while p1 and p2 are not empty a = p1.pop() b = p2.pop() if a == b: # if nodes are same update lowest common ancestor LCA = a else: break return LCA node1 = Node(10) node2 = Node(5) node3 = Node(2) node4 = Node(8) node5 = Node(20) node6 = Node(15) node1.left = node2 node1.right = node5 node2.parent = node1 node2.left = node3 node2.right = node4 node3.parent = node2 node4.parent = node2 node5.parent = node1 node5.left = node6 node6.parent = node5 print("Inorder: ", end=" ") inorder(node1) print() print("Preorder: ", end=" ") preorder(node1) print() print("Postorder: ", end=" ") postorder(node1) print() ## ============================================================================= # Maximum Height or depth in a tree def dfs_visit(node, visited, level, i): if node.left is not None: visited.add(node.left) #level[node.left.value] = i+1 level.add(i+1) dfs_visit(node.left, visited, level, i+1) if node.right is not None: visited.add(node.right) #level[node.right.value] = i+1 level.add(i+1) dfs_visit(node.right, visited, level, i+1) def maxi_height(T): """ Returns the maximum height of the given tree """ visited = set([T.root]) if T.root is None: return 0 #level = {T.root.value: 0} level = set([1]) dfs_visit(T.root, visited, level, 1) return max(level) def max_depth_simplified(node): """ Returns the maximum depth of the tree """ # Base case if node is None: return 0 # recurse on the left subtree left = max_depth_simplified(node.left) # recurse on the right subtree right = max_depth_simplified(node.right) return max(left, right) + 1 T = BinarySearchTree() T.root = node1 maxi_height(T) ## ============================================================================= ## Another Example one = Node(1) two = Node(2) three = Node(3) four = Node(4) five = Node(5) one.right = three one.left = two two.left = four two.right = five T = BinarySearchTree() T.root = one print("Maximum Height: ", maxi_height(T)) print("Maximum Depth: ", max_depth_simplified(one)) ## ============================================================================= def maximum_height_iteratively(node): if node is None: return 0 max_height = 1 stack = [(node, 1)] while stack: a = stack.pop() if a[0].left is not None: stack.append((a[0].left, a[1]+1)) if a[0].right is not None: stack.append((a[0].right, a[1]+1)) if a[1] > max_height: max_height = a[1] return max_height print("Maximum Height: ", maximum_height_iteratively(one))
""" Evaluate Reverse Polish Notation - https://leetcode.com/problems/evaluate-reverse-polish-notation/ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 """ class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack = [] for token in tokens: print(stack) if token in ['/', '*', '+', '-']: a = stack.pop() b = stack.pop() print(b,a,token) if token == '/': if (b < 0 and a > 0) or (a < 0 and b > 0): stack.append(-int(abs(b) / abs(a))) else: stack.append(int(b / a)) elif token == '*': stack.append(b * a) elif token == '-': stack.append(b - a) else: stack.append(b + a) else: stack.append(int(token)) return stack.pop() # a = Solution() # print(a.evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]))
""" Island Perimeter - https://leetcode.com/problems/island-perimeter You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 """ class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ def count_neighbours(grid, x, y): c = 0 # upper neighbours if x > 0: if grid[x-1][y] == 1: c += 1 # lower neighbours if x < len(grid)-1: if grid[x+1][y] == 1: c += 1 # left neighbours if y > 0: if grid[x][y-1] == 1: c += 1 # right neighbours if y < len(grid[0])-1: if grid[x][y+1] == 1: c += 1 return c peri = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: nh = count_neighbours(grid, i, j) if nh == 3: peri += 1 elif nh == 2: peri += 2 elif nh == 1: peri += 3 elif nh == 0: peri += 4 return peri
""" Hamming Distance - https://leetcode.com/problems/hamming-distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ? ? The above arrows point to positions where the corresponding bits are different. """ class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ bx = bin(x) by = bin(y) print(bx, by) if bx[0] == '-': bx = bx[3:] else: bx = bx[2:] if by[0] == '-': by = by[3:] else: by = by[2:] distance = 0 if len(bx) < len(by): bx = "0" * (len(by) - len(bx)) + bx if len(by) < len(bx): by = "0" * (len(bx) - len(by)) + by print(bx, by) for i in range(len(bx)): if bx[i] != by[i]: distance += 1 return distance def hammingDistance2(self, x, y): # Using bitwise XOR return bin(x^y).count('1')
""" Same Tree - https://leetcode.com/problems/same-tree Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ def inorder(root, path, string): if root: inorder(root.left, path, "left") path.append((root.val, string)) inorder(root.right, path, "right") # calculate inorder traversal of both of the given trees with their # node position values and compare them path1 = [] inorder(p, path1, "val") path2 = [] inorder(q, path2, "val") return path1==path2 a = Solution() t = TreeNode(10) r = TreeNode(10) t.right = r x = TreeNode(10) y = TreeNode(10) x.left = y print(a.isSameTree(t, x))
""" Base 7 - https://leetcode.com/problems/base-7 Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will be in range of [-1e7, 1e7]. """ class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ if num == 0: return "0" if num > 0: v = [] while num != 0: v.append(str(num%7)) num = num // 7 return "".join(v[::-1]) else: num = abs(num) v = [] while num != 0: v.append(str(num%7)) num = num // 7 return "-"+"".join(v[::-1])
""" Max Consecutive Ones - https://leetcode.com/problems/max-consecutive-ones Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The input array will only contain 0 and 1. The length of input array is a positive integer and will not exceed 10,000 """ class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ maxi = 0 sofar = 0 for i in nums: if i == 1: sofar += 1 if sofar > maxi: maxi = sofar else: sofar = 0 return maxi def findMaxConsecutiveOnes2(self, nums): """ :type nums: List[int] :rtype: int """ a = "".join(list(map(str, nums))).split("0") return len(max(a, key=lambda x:len(x)))
""" Average of Levels in Binary Tree - https://leetcode.com/problems/average-of-levels-in-binary-tree/ Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. Note: The range of node's value is in the range of 32-bit signed integer. """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ def inorder(root, level, avg): if root: if level in avg: avg[level].append(root.val) else: avg[level] = [root.val] inorder(root.left, level + 1, avg) inorder(root.right, level + 1, avg) avg = {} inorder(root, 0, avg) if avg == {}: return [] res = [] for i in range(max(avg)+1): x = sum(avg[i]) / len(avg[i]) res.append(x) return res # a = Solution() # t1 = TreeNode(3) # t2 = TreeNode(9) # t3 = TreeNode(20) # t4 = TreeNode(15) # t5 = TreeNode(7) # t1.left = t2 # t1.right = t3 # t3.left = t4 # t3.right = t5 # print(a.averageOfLevels(None))
""" Minimum Spanning Tree using Kruskal's and Prim's Algorithm """ from collections import defaultdict import heapq class Graph: def __init__(self, v): self.vertices = v self.graph = [] def add_edge(self, u, v, w): self.graph.append([u,v,w]) # find and union are used to quickly find whether including an edge will # form a cycle or not. def find(self, parent, i): """ find using path compression """ if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, i, j): """ union by rank """ x = self.find(parent, i) y = self.find(parent, j) if rank[x] < rank[y]: parent[x] = y elif rank[y] < rank[x]: parent[y] = x else: parent[y] = x rank[y] += 1 def kruskal(self): """ Kruskal's Algorithm to find the MST """ result = [] self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [i for i in range(self.vertices)] ranks = [0]*self.vertices # i for edges, e for mst i = e = 0 while e < self.vertices - 1: u,v,w = self.graph[i] i += 1 x = self.find(parent, u) y = self.find(parent, v) if x != y: e += 1 result.append([u,v,w]) self.union(parent, ranks, x, y) print(result) G = Graph(4) G.add_edge(0, 1, 10) G.add_edge(0, 2, 6) G.add_edge(0, 3, 5) G.add_edge(1, 3, 15) G.add_edge(2, 3, 4) G.kruskal() d = {0: [1,7], 1:[0, 2,7], 2:[1,3,5,8], 3:[2,4,5], 4:[3,5], 5:[2,3,4,6], 6:[5,7,8], 7:[0,1,6,8], 8:[2,6,7]} w = {(0,1): 4, (0,7): 8, (1,2):8, (1,7):11, (2,3):7,(2,5):4,(2,8):2,(3,4):9,(3,5):14,(4,5):10,(5,6):2,(6,7):1,(6,8):6,(7,8):7} ## ============================================================================= ## Prim's Algorithm class MinHeap: """ A min-heap to use in prim's algorithm """ def __init__(self, h): self.heap = h # prototype -> [(dist1, node1), (dist2, node2)..] self.heap_size = len(h) self.pos = {h[i][1]:i for i in range(len(h))} def left(self, i): return 2*i+1 def right(self, i): return 2*i+2 def parent(self, i): return i//2 def min_heapify(self, i): l = self.left(i) r = self.right(i) if l < self.heap_size and self.heap[l][0] < self.heap[i][0]: smallest = l else: smallest = i if r < self.heap_size and self.heap[r][0] < self.heap[smallest][0]: smallest = r if smallest != i: self.heap[smallest], self.heap[i] = self.heap[i], self.heap[smallest] self.pos[self.heap[smallest][1]] = smallest self.pos[self.heap[i][1]] = i self.min_heapify(smallest) def build_min_heap(self): self.heap_size = len(self.heap) for i in range(len(self.heap)//2+1, -1, -1): self.min_heapify(i) def extract_min(self): if self.heap_size < 1: raise "Heap is Empty!" mini = self.heap[0] self.heap[0], self.heap[self.heap_size-1] = self.heap[self.heap_size-1], self.heap[0] self.pos[self.heap[0][1]] = 0 self.pos[self.heap[self.heap_size-1][1]] = self.heap_size-1 self.heap_size -= 1 self.min_heapify(0) return mini def decrease_key(self, i, key): if self.heap[i][0] < key: return False self.heap[i][0] = key #print(self.heap[self.parent(i)], self.heap[i]) while i >= 0 and self.heap[i][0] < self.heap[self.parent(i)][0]: self.heap[i], self.heap[self.parent(i)] = self.heap[self.parent(i)], self.heap[i] self.pos[self.heap[i][1]] = i self.pos[self.heap[self.parent(i)][1]] = self.parent(i) i = self.parent(i) return True def insert_key(self, dist, node): if self.heap_size < len(self.heap): self.heap[self.heap_size] = [float('inf'), node] else: self.heap.append([float('inf'), node]) self.heap_size += 1 self.pos[node] = self.heap_size-1 self.decrease_key(self.heap_size-1, dist) def find_key(self, key): return self.pos.get(key, -1) def is_empty(self): return self.heap_size == 0 def prim(d,w,s): """ Prim's algorithm to find the minimum spanning tree. """ heap = MinHeap([[0, s]]) dist = [float('inf')]*len(d) visited = set() dist[s] = 0 while not heap.is_empty(): dis, u = heap.extract_min() visited.add(u) for v in d[u]: if v not in visited: if dist[v] > w[min(u,v), max(u,v)]: dist[v] = w[min(u,v), max(u,v)] pos = heap.find_key(v) if pos != -1: heap.decrease_key(pos, dist[v]) else: heap.insert_key(dist[v], v) print(dist) prim(d,w,0) ## =============================================================================
""" Set Mismatch - https://leetcode.com/problems/set-mismatch The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array. Example 1: Input: nums = [1,2,2,4] Output: [2,3] Note: The given array size will in the range [2, 10000]. The given array's numbers won't have any order. """ class Solution(object): def findErrorNums(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) first = sum(nums) - n * (n + 1) / 2 second = (sum(i*i for i in nums) - n * (n+1)*(2*n+1) / 6) / first return (first + second) / 2, (second - first) / 2
''''''''''''''''''''''''''''''''''''''''''''''''''' > System: Ubuntu > Author: ty-l8 > Mail: liuty196888@gmail.com > File Name: insertsort.py > Created Time: 2017-09-22 Fri 10:58 ''''''''''''''''''''''''''''''''''''''''''''''''''' # insert sort using binarySearch written by lty, which time complexity is O(nlogn) from binarySearch import binarySearch def insertSort(array): result = [] for elem in array: result.insert(abs(binarySearch(elem, result)), elem) return result def normalInsertSort(array): length = len(array) if length<=1: return array for i in range(1, length): for j in range(i-1, 0, -1): if array[j]<array[i]: break array[i], array[j] = array[j], array[i] return array def recursiveInsertSort(array, result): if len(result) >= len(array): return result elem = array[len(result)] result.insert(abs(binarySearch(elem, result)), elem) return recursiveSelectSort(array, result)
#!bin/python3 #Variables and methods quote = "All is fair in love and war." print(quote.upper()) #uppercase print(quote.lower()) #lowercase print(quote.title()) #title case print(len(quote)) name = "amani" #string age = 21 #int gpa = 3.7 #float print(int(age)) print(int(30.1)) print("My name is " + name + " and I am " + str(age) + " years old.") age += 1 print(age) birthday = 1 age += birthday print(age) print('\n') #Functions print ("Here is an example function:") def who_am_i(): #this is a function name = "Amani" age = 21 print("My name is " + name + " and I am " + str(age) + " years old.") who_am_i() #adding parameters def add_one_hundred(num): print(num + 100) add_one_hundred(100) #multiple parameters def add(x,y): print(x + y) add(7, 7) def multiply(x, y): return x * y print(multiply(7, 7)) def square_root(x): print(x ** .5) square_root(64) def nl(): print('\n') nl() #Boolean expressions (True or False) print("Boolean expressions:") bool1 = True bool2 = 3*3 == 9 bool3 = False bool4 = 3*3 != 9 print(bool1,bool2,bool3,bool4) print(type(bool1)) nl() #Relational and Boolean operators greater_than = 7 > 5 less_than = 5 < 7 greater_than_equal_to = 7 >= 7 less_that_equal_to = 7 <= 7 test_and = (7 > 5) and (5 < 7) #True test_and2 = (7 > 5) and (5 > 7) #False test_or = (7 > 5) or (5 < 7) #True test_or2 = (7 > 5) or (5 > 7) #True test_not = not True#False nl() #conditional statements def drink(money): if money >= 2: return "You've got yourself a drink!" else: return "NO drink for you!" print(drink(3)) print(drink(1)) def alcohol(age, money): if (age >= 21) and (money >= 5): return "We're getting a drink!" elif (age >= 21) and (money < 5): return "Come back with more money." elif (age < 21) and (money>= 5): return "NIce try, kid!" else: return "You're too poor and too young" print(alcohol(21, 5)) print(alcohol(21, 4)) print(alcohol(20,4)) nl() #List - Have brackets [] and are mutable movies = ["Kill Bill", "The wolf of wallstreet", "as above so below", "The hangover"] print(movies[0]) #return the second item print(movies[1]) #return the first item in the list print(movies[1:4]) print(movies[1:]) print(movies[:1]) print(movies[:-1]) print(len(movies)) movies.append("jaws") print(movies) movies.pop() print(movies) movies.pop(0) print(movies) nl() #Tuples - Do not change, () are immutable grades = ("a", "b", "c", "d", "f") print(grades[1]) nl() #Looping #For loops - start to finish of an iterate vegetables = ["cucumber", "spinach", "cabbage"] for x in vegetables: print(x) #while loops - execute as long as true i = 1 while i < 10: print(i) i += 1
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Tools used to manipulate continued fractions Function names are converters from one number representation to another. bits: list of bits, the most significant one coming first. dec: float. cfrac: list of integers appearing in a continued fraction. The first element is the first integer, [a, b, c] corresponds to 1(a+1/(b+1/(c))). frac: a pair (numerator, denominator) """ def bits_to_dec(l): """ Convert a number from a bit to decimal (float) representation. l is a list of bits, the most significant one coming first. bits_to_dec([]) -> 0 """ if l == []: return 0 else: return 0.5*l[0] + 0.5*bits_to_dec(l[1:]) def dec_to_cfrac(d, t): """ Give the continued fraction decomposition of a float. d is the number to decompose, 0<t<1 is a threshold. If a number lower than this value appears in the decomposition, the algorithm truncates it and stops. """ if d < t: return [] return [int(1/d)] + dec_to_cfrac(1/d-int(1/d), t) def cfrac_to_frac(l): """ Give the numerator and denominatior of a continued fraction. The function returns a pair (numerator, denominatior) """ num = 0 den = 1 for r in reversed(l): num, den = den, num + r*den return num, den def dec_to_frac(d, t): """ Turn a decimal number into a fraction The continued fraction decomposition (with a truncation) is used. d is the number to decompose, 0<t<1 is a threshold. If a number lower than this value appears in the decomposition, the algorithm truncates it and stops. """ return cfrac_to_frac(dec_to_cfrac(d, t)) def bits_to_frac(l, t): """ Turn a binary number into a fraction The continued fraction decomposition (with a truncation) is used. b is the number to decompose, a list of bits (the most significant one coming first). 0<t<1 is a threshold. If a number lower than this value appears in the decomposition, the algorithm truncates it and stops. """ return dec_to_frac(bits_to_dec(l), t)
"""https://www.codeeval.com/open_challenges/21/""" import sys test_cases = open(sys.argv[1], 'r') def sum_digits(n): n = int(n) sum = 0 while (n/10 > 0): sum += n%10 n = n//10 print(sum) for test in test_cases: sum_digits(test) test_cases.close()
"""https://www.codeeval.com/open_challenges/20/""" import sys test_cases = open(sys.argv[1], 'r') def convert_lowercase(s): print(s.lower()) for test in test_cases: convert_lowercase(test) test_cases.close()
#!/usr/bin/python # Create a list of 5 IPs ip_list = ["10.1.2.4", "172.16.15.9", "154.69.45.26", "10.5.7.1", "10.7.96.5"] print(ip_list) # use append to add an ip to the end of the list ip_list.append("192.65.8.2") print(ip_list) # user extend to add two more ips to the end new_ips = ["192.168.1.1", "192.168.1.2"] ip_list.extend(new_ips) print(ip_list) # print the list, print the first ip and print the last ip print(ip_list[0]) print(ip_list[-1]) # use pop to remove the first and last ip in the list ip_list.pop(0) ip_list.pop(-1) # update the first ip in the list to 2.2.2.2, print out the new first ip ip_list.insert(0, "2.2.2.2") print(ip_list[0])
from game import * from collections import deque # Project main loop def game(levels): game = Game(levels) intro = run = True computer = human = choosingLevel = False while run: #MAIN MENU while intro: game.writeToScreen(center, "Press H to play in human mode. ", True) game.writeToScreen((center[0], center[1] + 30), "Press C to play in computer mode. ", False) pygame.display.flip() input = game.checkInputs([pygame.K_h, pygame.K_c]) # check mouse events if input == pygame.K_h: human = True if input == pygame.K_c: computer = True if (human or computer): intro = False choosingLevel = True game.writeToScreen(center, "", True) levelNotChosen = True #choose level to play while choosingLevel: if levelNotChosen: game.writeToScreen(center, "What level would you like to play?", False) game.writeToScreen((center[0], center[1] + 50), "Select from 1 to " + str(len(levels)), False) pygame.display.flip() # check mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() #check level chosen elif event.type == pygame.KEYDOWN: level = pygame.key.name(event.key) if level >= '1' and level <= str(len(levels)): game.setLevel(int(level)) choosingLevel = False else: game.writeToScreen((center[0], center[1] - 50), "That level doesn't exist", False) levelNotChosen = True selection = "" if(human): while True: selection = game.playHuman() if selection == "Main menu": intro = run = True computer = human = choosingLevel = False break if selection == "Play again": game = Game(levels) game.setLevel(int(level)) elif(computer): while True: selection = game.playComputer() if selection == "Main menu": intro = run = True computer = human = choosingLevel = False break while selection != "Main menu": # check mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() touchesLeft = 5 startGrid = [] grid1 = [] grid2 = [] grid1.append([1, 0, 0, 4, 1]) grid1.append([0, 1, 0, 1, 0]) grid1.append([0, 0, 1, 0, 0]) grid1.append([0, 0, 0, 0, 0]) grid1.append([0, 1, 0, 1, 0]) grid1.append([1, 1, 0, 0, 1]) grid2.append([1, 1, 0, 2, 1]) grid2.append([1, 1, 1, 1, 2]) grid2.append([1, 1, 3, 2, 0]) grid2.append([1, 1, 3, 2, 1]) grid2.append([0, 0, 4, 1, 0]) grid2.append([1, 0, 2, 2, 0]) newGrid = [[1, 1, 1, 4, 2], [4, 3, 3, 4, 0], [1, 1, 0, 2, 1], [1, 1, 3, 4, 3], [0, 0, 4, 1, 0], [2, 0, 3, 2, 0]] startGrid.append([1, 1, 1, 1, 1]) startGrid.append([1, 2, 0, 0, 0]) startGrid.append([1, 0, 0, 0, 0]) startGrid.append([1, 0, 0, 0, 0]) startGrid.append([1, 0, 0, 0, 0]) startGrid.append([1, 0, 0, 0, 0]) def parseLevels(file): levels = [] rawFile = [] newLevel = [] wroteLevel = wroteTouches = wroteSol = False with open(file) as my_file: rawFile = my_file.read().splitlines() for line in rawFile: if not wroteLevel: del newLevel[:] newLevel.append(int(line[-1:])) newLevel.append([]) newLevel.append([]) newLevel.append([]) wroteLevel = True elif not wroteTouches: newLevel[2] = int(line) wroteTouches = True elif not wroteSol: sol = line.split(';') for move in sol: newLevel[3].append(list(map(int, move.split(",")))) wroteSol = True elif len(newLevel[1]) < 6: newLine = list(map(int, line.split())) newLevel[1].append(newLine) if len(newLevel[1]) == 6: levels.append(copy.deepcopy(newLevel)) wroteLevel = wroteTouches = wroteSol = False return levels game(parseLevels("Levels.txt"))
time = [] while True: jogador = {} jogador = {'Nome':input('Nome: '), 'Partidas':int(input('Partidas jogadas: ')), } total_gols = 0 Gols = [] for p in range(0, jogador['Partidas']): gol = int(input(f'Gols marcados na partida {p+1}: ')) Gols.append(gol) total_gols += gol jogador['Total de Gols'] = total_gols jogador['Gols por Partida'] = Gols[:] time.append(jogador.copy()) while True: r = input('Continuar? [S/N] ').upper()[0] if r in 'SN': break print('ERRO! Preencha com S (sim) ou N (não).') if r == 'N': break print() print(f'{"No":<4}{"Nome":<10}{"Gols":>10}{"Total":>30}') print('='*55) for i,j in enumerate(time): print(f'{i:<4}{j["Nome"]:<10}', end=' ') print(f'{j["Gols por Partida"]}', end=' ') print(f'{j["Total de Gols"]}') while True: while True: resp = int(input('Mostrar desempenho de qual jogador? ')) if resp <= len(time): break print('ERRO! Jogador inexistente.') if resp == 999: break print('--Desempenho do Jogador--') for j, g in enumerate(time[resp]["Gols por Partida"]): print(f'No jogo {j+1} marcou {g} gols')
#Escopo de variáveis. Aula 21 Python Mundo 3 #Escopo local def teste(): x = 8 #Foi declarada dentro da função, logo a variável é local. Só vai funcionar nessa área. d = 1 #Cria uma variável nova. Local. Diferente do d global. print(f'Na função teste, a variável local x tem valor {x}') print(f'Na função teste, a variável global n tem valor {n}') print(f'Na função teste, a variável local d tem valor {d}') #Escopo global: d = 5 n = 4 print(f'No programa principal, n global vale {n}') #print(f'No programa principal, x vale {x}'). Vai dar erro, pois x é uma variável local. print(f'No programa principal, d global vale {d}') teste() print('\nEu também posso optar por alterar a variável global d dentro da minha função, em vez de o python criar uma versão local dela:') def teste2(): global d d = 2 print(f'Na função teste2, d global vale {d}') print(f'No programa principal, d global também vale {d}')
#TRABALHANDO COM STRINGS #CONTA A QUANTIDADE DE LETRA A NUMA FRASE E INDICA SUAS POSIÇÕES while True: frase = input("Digite uma frase: ").strip().upper() if "SAIR" == frase: print("saiu", "\n") break elif "SAIR" != frase: print("ANALISANDO FRASE...") print("A letra A aparece {} vezes na frase".format(frase.count("A"))) print("A primeira letra A apareceu na posição {}".format(frase.find("A"))) #find() indica a posição. Procura a partir do lado esquerdo. print("A última letra A apareceu na posição {}".format(frase.rfind("A")), "\n") #rfind() indica a posição. Procura a partir do lado direito.
#DESAFIO DO PROCESSO SELETIVO DE 2020 - JAGUAR #Mabe S2 dados = [] #lista vazia dos dados while True: #dados = [] #lista vazia dos dados nome = input("Digite seu nome: ").strip().upper() #usuario digita um nome. strip() elimina os espaços. if nome == "SAIR": #Se o usuario digitar sair, para a execucao print("voce saiu!") break if nome != "SAIR": #Se o usuario entrar com um nome, continua dados.append(nome) #insere o nome na lista idade = int(input("Digite a sua idade: ")) #usuario digita uma idade #Foi utilizado int() para tratar a idade como numero inteiro #Se estiver usando Python 2, utilize raw_input() if idade <18: idade = "menor de idade" dados.append(idade) #insere a idade na lista print(dados) elif idade >=18 and idade <65: idade = "maior de idade" dados.append(idade) print(dados) else: idade = "idoso" dados.append(idade) print(dados)
#MaBe #Função que calcula a área de um terreno retangular def area(largura, comprimento): area = largura*comprimento print(f'A área do terreno é {area}m².') b = float(input('Largura [m]: ')) h = float(input('Comprimento [m]: ')) area = area(b, h)
#LÊ UM NOME COMPLETO E DIZ QUAL O PRIMEIRO NOME E QUAL O ÚLTIMO NOME while True: nome = input("Digite seu nome completo: ").upper().strip() n1 = nome.split() #fatia o nome. Divide em partes. Joga para uma lista. ult = len(n1) - 1 #len() conta as posições da lista. Me da a quantidade. ult = n1[ult] #fornece o útimo nome prim = n1[0] #posição 0 da lista é o primeiro nome if nome == "SAIR": print("saiu", "\n") break elif nome != "SAIR": print("Seu primeiro nome é {}".format(prim), "\nSeu último nome é {}".format(ult), "\n" )
# Methacaracter plus + # Usado para uma ou mais correspondencias do padrao restante import re txt = 'maaano' x = re.findall('ma+n', txt) print (x)
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-compute-a-power-b '''Given 2 numbers - a and b, evaluate ab. Input Format First line of input contains T - number of test cases. Its followed by T lines, each line containing 2 numbers - a and b, separated by space. Constraints 30 points 1 <= T <= 1000 0 <= a <= 106 0 <= b <= 103 70 points 1 <= T <= 1000 0 <= a <= 106 0 <= b <= 109 Output Format For each test case, print ab, separated by new line. Since the result can be very large, print result % 1000000007 Sample Input 0 4 5 2 1 10 2 30 10 10 Sample Output 0 25 1 73741817 999999937 ''' _author_ = "sheetansh" def aPowerb(a, b): if (b==0): return 1 store = aPowerb(a, b//2) if(b %2 == 0): return ((store%1000000007)*(store%1000000007))%1000000007 else: return (a*((store%1000000007)*(store%1000000007))%1000000007)%1000000007 t = int(input()) for _ in range(t): l = list(map(int, input().split())) print(aPowerb(l[0], l[1])%1000000007)
def flipBits(n): res = "" for _ in range(32): res = res + str((n&1)^1) n = n>>1 return (int(res[::-1],2)) def flippingBits(n): return ((1<<32)-1)-n def flippingBits2(n): return ((1<<32)-1)^n if __name__ == '__main__': n = 4 print("{:032b}".format(n)) print(flipBits(n)) print("{:032b}".format(flipBits(n))) print("{:032b}".format(flippingBits2(n)))
''' https://www.interviewbit.com/problems/min-jumps-array/ Given an array of non-negative integers, A, of length N, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Return the minimum number of jumps required to reach the last index. If it is not possible to reach the last index, return -1. Input Format: The first and the only argument contains an integer array, A. Output Format: Return an integer, representing the answer as described in the problem statement. Constraints: 1 <= N <= 1e6 0 <= A[i] <= 50000 Examples: Input 1: A = [2, 1, 1] Output 1: 1 Explanation 1: The shortest way to reach index 2 is Index 0 -> Index 2 that requires only 1 jump. Input 2: A = [2,3,1,1,4] Output 2: 2 Explanation 2: The shortest way to reach index 4 is Index 0 -> Index 1 -> Index 4 that requires 2 jumps. ''' def jump(self, arr): n = len(arr) dp = [0] * (n + 1) if (n == 1 and arr[0] == 0): return 0 idx = 0 i = 1 while i < n and idx < i: if idx + arr[idx] >= i: dp[i] = dp[idx] + 1 i += 1 else: idx += 1 if dp[n - 1] == 0: return -1 return dp[n - 1] '''public int minJump(int arr[],int result[]){ int []jump = new int[arr.length]; jump[0] = 0; for(int i=1; i < arr.length ; i++){ jump[i] = Integer.MAX_VALUE-1; } for(int i=1; i < arr.length; i++){ for(int j=0; j < i; j++){ if(arr[j] + j >= i){ if(jump[i] > jump[j] + 1){ result[i] = j; jump[i] = jump[j] + 1; } } } } return jump[jump.length-1]; }'''
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-rhymes '''Given is a wordlist L, and a word w. Your task is to find the length of the longest word in L having the longest common suffix with w. Input Format First line of input contains N - length of the list of words. The next N lines contains a single word having lowercase english alphabets. The next line contains Q - number of queries. Each of the next Q lines contains a single word w having lowercase english alphabets. Constraints 50 points 1 <= N, Q <= 1000 1 <= len(word) <= 100 150 points 1 <= N, Q <= 10000 1 <= len(word) <= 500 Output Format For each query w, print the length of the longest word having the longest common suffix with w, separated by newline. Sample Input 0 4 crime fast time cast 3 dime gist algorithm Sample Output 0 5 4 0 Explanation 0 Test Case 1 Both the words crime and time have the longest common suffix with dime. Hence, length of the longest word is 5. Test Case 2 Both the words fast and cast have the longest common suffix with gist. Hence, length of the longest word is 4. Test Case 3 There is no word in L having a common suffix with algorithm. Hence, length of the longest word is 0.''' _author_ = "sheetansh" n = int(input()) words = [] for _ in range(n): words.append(input()) q = int(input()) for _ in range(q): query = list(input()) max_len = 0 curr_len = 0 max_suff_len = 0 for i in words: if(i[-1] == query[-1]): curr_len = len(i) k = -1 while(abs(k) <= len(query)and abs(k) < len(i) and i[k] == query[k]): k-=1 if abs(k) > max_suff_len or ((abs(k) == max_suff_len) and curr_len > max_len): max_len = curr_len max_suff_len = abs(k) print(max_len)
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-find-first-repeating-character '''Given a string of characters, find the first repeating character. Input Format First line of input contains T - number of test cases. Its followed by T lines, each line contains a single string of characters. Constraints 1 <= T <= 1000 'a' <= str[i] <= 'z' 1 <= len(str) <= 104 Output Format For each test case, print the first repeating character, separated by newline. If there are none, print '.'. Sample Input 0 3 smartinterviews algorithms datastructures Sample Output 0 s . a ''' _author_ = "sheetansh" from collections import Counter t = int(input()) for _ in range(t): st = Counter(input()) flag = 1 for i in st.keys(): if st[i] >1: print(i) flag = 0 break if flag: print(".")
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-reverse-bits/submissions/code/1318356027 '''Given a number, reverse the bits in the binary representation (consider 32-bit unsigned data) of the number, and print the new number formed. Input Format First line of input contains T - number of test cases. Each of the next T lines contains a number integer N. Constraints 1 <= T <= 100000 0 <= N <= 109 Output Format For each test case, print the new number formed after reversing the bits, separated by new line. Sample Input 4 4 15 6 1000000000 Sample Output 536870912 4026531840 1610612736 5462492 Explanation Test Case 1 Binary Representation of 4: 000...100 After reversing the bits: 001...000 (536870912) Test Case 2 Binary Representation of 15: 000...1111 After reversing the bits: 1111...000 (4026531840)''' # solution _author_ = "sheetansh" '''get the last bit and add it to result''' for _ in range(int(input())): n = int(input()) res = 0 count = 31 while(n): res <<= 1 res = res | (n & 1) n >>= 1 count -= 1 res <<= (count + 1) print(res)
''' https://www.interviewbit.com/problems/min-sum-path-in-matrix/ Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example : Input : [ 1 3 2 4 3 1 5 6 1 ] Output : 8 1 -> 3 -> 2 -> 1 -> 1 ''' def minPathSum(self, arr): dp = [[0 for i in range(len(arr[0]))] for j in range(len(arr))] dp[0][0] = arr[0][0] for i in range(1, len(arr)): dp[i][0] = dp[i - 1][0] + arr[i][0] for i in range(1, len(arr[0])): dp[0][i] = dp[0][i - 1] + arr[0][i] for i in range(1, len(arr)): for j in range(1, len(arr[0])): dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + arr[i][j] return dp[len(arr) - 1][len(arr[0]) - 1]
def perform_bubble_sort(blist): cmpcount, swapcount = 0, 0 for j in range(len(blist)): for i in range(1, len(blist)-j): cmpcount += 1 if blist[i-1] > blist[i]: swapcount += 1 blist[i-1], blist[i] = blist[i], blist[i-1] return cmpcount, swapcount print(perform_bubble_sort([8,22,7,9,31,19,4,13]))
# Given a positive integer, print its binary representation. # # Input Format # # First line of input contains T - number of test cases. Its followed by T lines, each line containing a single integer. # # Constraints # # 1 <= T <= 10000 # 0 <= N <= 109 # # Output Format # # For each test case, print binary representation, separated by new line. # # Sample Input 0 # # 5 # 10 # 15 # 7 # 1 # 120 # # Sample Output 0 # # 1010 # 1111 # 111 # 1 # 1111000 t = int(input()) for _ in range(t): print(bin(int(input()))[2:])
def prettyPrint(n): ans = [] for i in range(n): temp = [] k = n for j in range(i): temp.append(k) k -= 1 temp = temp + ([n - i] * (n - i)) temp = temp + temp[::-1][1:] ans.append(temp) for i in range(1,n): ans.append(ans[n-i-1]) return ans a = prettyPrint(4) for i in a: print(i)
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-subsets-of-an-array/problem '''Given an array of unique integer elements, print all the subsets of the given array in lexicographical order. Input Format First line of input contains T - number of test cases. Its followed by 2T lines, the first line contains N - the size of the array and second line contains the elements of the array. Constraints 1 <= T <= 100 1 <= N <= 10 0 <= A[i] <= 100 Output Format For each test case, print the subsets of the given array in lexicographical order, separated by new line. Print an extra newline between output of different test cases. Sample Input 0 3 3 5 15 3 2 57 96 4 3 15 8 23 Sample Output 0 3 3 5 3 5 15 3 15 5 5 15 15 57 57 96 96 3 3 8 3 8 15 3 8 15 23 3 8 23 3 15 3 15 23 3 23 8 8 15 8 15 23 8 23 15 15 23 23 ''' _author_ = "sheetansh" def subsetUtil(arr, tempres, idx): # res.append(tempres) # print(res) if (tempres != None and tempres != []): print(*tempres) for i in range(idx, len(arr)): tempres.append(arr[i]) subsetUtil(arr, tempres, i + 1) tempres.pop() return def subset(A): tempres = [] subsetUtil(A, tempres, 0) for _ in range(int(input())): # n = int(input()) # arr = list(map(int, input().split())) # arr.sort() subset([1,2,3]) print()
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-check-anagrams '''Given 2 strings, check if they are anagrams. An anagram is a rearrangement of the letters of one word to form another word. In other words, some permutation of string A must be same as string B. Input Format First line of input contains T - number of test cases. Its followed by T lines, each line containing 2 space separated strings. Constraints 10 points 1 <= T <= 100 1 <= len(S) <= 103 'a' <= S[i] <= 'z' 40 points 1 <= T <= 100 1 <= len(S) <= 105 'a' <= S[i] <= 'z' Output Format For each test case, print True/False, separated by newline. Sample Input 0 4 a a b h stop post hi hey Sample Output 0 True False True False ''' _author_ = "sheetansh" from collections import Counter t = int(input()) for _ in range(t): arr = input().split() print(Counter(arr[0]) == Counter(arr[1]))
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-distinct-elements-in-window '''Given an array of integers and a window size K, find the number of distinct elements in every window of size K of the given array. Input Format First line of input contains T - number of test cases. Its followed by 2T lines. First line of each test case contains N - size of the array and K - size of the window. The second line contains N integers - elements of the array. Constraints 1 <= T <= 1000 1 <= N <= 10000 1 <= K <= N -100 <= ar[i] <= 100 Output Format For each test case, print the number of distinct elements in every window of size K, separated by newline. Sample Input 0 3 5 3 -2 -4 -2 4 -2 10 7 3 -4 -3 -4 -2 0 2 -2 6 0 17 13 -5 -1 4 8 -5 -3 -4 7 4 -4 0 8 0 -2 3 2 5 Sample Output 0 2 3 2 6 5 6 5 8 9 9 10 11 ''' _author_ = "sheetansh" from collections import Counter for _ in range(int(input())): n, k = list(map(int, input().split())) arr = list(map(int, input().split())) res = [] i, j = 0, k-1 m = dict(Counter(arr[i:j+1])) res.append(len(m)) while(j != n-1): i+=1 j+=1 m[arr[i-1]]-=1 if(m[arr[i-1]] == 0): del m[arr[i-1]] try: m[arr[j]] +=1 except: m[arr[j]] = 1 res.append(len(m)) print(*res)
''' https://www.hackerrank.com/contests/smart-interviews-16b/challenges/si-range-sum-subarrays Given an array of integers and a range [A,B], you have to find the number of subarrays whose sum lies in the given range inclusive. Input Format First line of input contains T - number of test cases. Its followed by 2T lines, the first line of each test case contains N, A, B - size of the array and the range separated by space, the second line contains the elements of the array. Constraints 30 points 1 <= T <= 100 1 <= N <= 100 -106 <= A <= B <= 106 -104 <= ar[i] <= 104 70 points 1 <= T <= 100 1 <= N <= 1000 -107 <= A <= B <= 107 -104 <= ar[i] <= 104 Output Format For each test case, print the number of subarrays whose sum lies in the given range, separated by newline. Sample Input 0 4 3 -10 5 -5 10 -3 4 -10000 1000 929 -4041 -2470 -6445 9 -36116 6820 4605 -626 -3454 -2532 -91 3010 -3557 5552 4055 6 392 5416 -4905 -2388 5352 -3231 4902 -7485 Sample Output 0 4 8 41 6 Explanation 0 Test Case 1: The subarrays are: -5 [Sum = -5] -5 10 [Sum = 5] -5 10 -3 [Sum = 2] 10 [Sum = 10] 10 -3 [Sum = 7] -3 [Sum = -3] Hence, there are 4 subarrays whose sum lie in the range [-10,5] Contest ends in 3 hours Submissions: 21 Max Score: 100 Difficulty: Easy Rate This Challenge: More '''
# Metodo count() ## Busca un elemento en una tupla y retorna el ## número de veces que se repita # t = (0, 1, 2, 3, 2, 4, 5, 2, 2) # print(t.count(2)) # print(t.count(5)) # a = ('manuel','oscar','manuel') # print(a.count('manuel')) # tupla = ('Curso', 15, True, 150.20, 150.20, False, 'Alumno') # print(tupla.count('Alumno')) #Imprime 1 # # Metodo index() # ## Busca el elemento en una tupla y retorna el # # ## número indice # t = (0, 1, 2, 3, 2, "Z", 4, 5, 2, 2) #print(t.index("Z")) # # Unpack # ## Se puede asiganr los valores de una tupla a variables # t = ("manzana", "pera", "naranja", "uva") # (s1, s2, s3, s4) = t # # # #Imprimimos el elemento ceo 0 # print(t[2]) # Imprime manzana # # # # Imprimimos la variable s1 # print(s3) # # Actualización # ## Los elementos de las tuplas no pueden ser actulizados # # ## a diferencia de las listas que si se puede # profesor = ("Yosip", "Urquizo", "Gómez") # #profesor[1] = "Morales" # Genera un error al ejecutar # # ## Pero si podemos concatenar una tupla con otra # direccion = ("Victor Larco", "Trujillo") # datos_del_profesor = profesor + direccion # print(datos_del_profesor) # # Operaciones # ## Las tuplas responden a los signos + y * # ## + significa concatenacion # # ## * significa repeticion a = (1, 2, 3, 4, 5, 6, 7, 8) b = (4, 5, 6) # longitud = len(a + b) # print(longitud) # 3 # concatenar = a + b # print(concatenar) # 1,2,3,4,5,6 # afiliacion = 7 in a # print(afiliacion) # True # # #iteraccion for xy in (a+b):print(xy, end='')
# # This file contains the Python code from Program 12.8 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm12_08.txt # class SetAsBitVector(Set): def __or__(self, set): assert isinstance(set, SetAsBitVector) assert self._universeSize == set._universeSize result = SetAsBitVector(self._universeSize) for i in xrange(len(self._vector)): result._vector[i] = self._vector[i] | set._vector[i] return result def __and__(self, set): assert isinstance(set, SetAsBitVector) assert self._universeSize == set._universeSize result = SetAsBitVector(self._universeSize) for i in xrange(len(self._vector)): result._vector[i] = self._vector[i] & set._vector[i] return result def __sub__(self, set): assert isinstance(set, SetAsBitVector) assert self._universeSize == set._universeSize result = SetAsBitVector(self._universeSize) for i in xrange(len(self._vector)): result._vector[i] = self._vector[i] & ~set._vector[i] return result # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import itertools def start_at_three(): val = input("input some words or numbers: ").strip() while val != '': for el in itertools.islice(val.split(), 2, None): yield el val = input("input some words or numbers: ").strip() def itertools_tee(iterable, headsize=1): a, b = itertools.tee(iterable) return list(itertools.islice(a, headsize)), b def itertools_groupby(data = None): if data is None: return None return ((len(list(group)), name) for name, group in itertools.groupby(data)) def main(): print("hello, itertools") s_at_3 = start_at_three() print(next(s_at_3)) print(next(s_at_3)) print(next(s_at_3)) seq = [x for x in range(10)] print(str(itertools_tee(seq))) print(str(itertools_tee(seq, 3))) print(list(itertools_groupby("hello, world, taowuwen"))) print("".join(size*name for size, name in itertools_groupby("hello, world, taowuwen"))) if __name__ == '__main__': main()
# # This file contains the Python code from Program 6.13 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm06_13.txt # class QueueAsArray(Queue): def getHead(self): if self._count == 0: raise ContainerEmpty return self._array[self._head] def enqueue(self, obj): if self._count == len(self._array): raise ContainerFull self._tail = self._tail + 1 if self._tail == len(self._array): self._tail = 0 self._array[self._tail] = obj self._count += 1 def dequeue(self): if self._count == 0: raise ContainerEmpty result = self._array[self._head] self._array[self._head] = None self._head = self._head + 1 if self._head == len(self._array): self._head = 0 self._count -= 1 return result # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import time import pygame import math from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600, 500)) pygame.display.set_caption("Draw Arcs") def draw_arc(): color = 255, 0, 255 width = 8 pos = 200, 150, 200, 100 start_angle = math.radians(0) end_angle = math.radians(150) pygame.draw.rect(screen, (100, 100, 100), pos, width) pygame.draw.ellipse(screen, color, pos, width) while True: for evt in pygame.event.get(): if evt.type in (QUIT, KEYDOWN): sys.exit() screen.fill((0, 0, 120)) draw_arc() pygame.display.update()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- seconds_per_hour = 60 * 60 print("seconds_per_hour = ", seconds_per_hour); seconds_per_day = seconds_per_hour * 24; print("seconds_per_day = ", seconds_per_day); print("seconds_per_day / seconds_per_hour = ", seconds_per_day / seconds_per_hour); print("seconds_per_day // seconds_per_hour = ", seconds_per_day // seconds_per_hour);
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def finally_test_trap_one(): print("hello, finally test ---> trap 1") while True: try: raise ValueError("this is value error") except NameError as e: print("NameErorr {}".format(e)) break finally: print("Finally here, should never 'break' here") break def finally_test_trap_two(arg=0): print("hello, finally test ---> trap 2") try: if arg <= 0: raise ValueError("Value Error here") else: return 1 except ValueError as e: print(e) finally: print("The End -1, should never do 'RETURN' in finally") return -1 def main(): print("hello, finally test") finally_test_trap_one() finally_test_trap_two(0) finally_test_trap_two(1) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #years_list = [ y for y in range(1987, 1987 + 6) ] years_list = [ y + 1987 for y in range(6) ] #years_list = list(range(1987, 1987 + 6)); print(years_list) print("birthday = ", years_list[0]) print("oldest = ", years_list[-1]) things = ["mozzarella", "cinderella", "salmonella" ] print(things) for word in things: print(word, "capitalize() = ", word.capitalize()) print(things) for word in things: print(word, "upper() = ", word.upper()) del things[0]; print(things) things.remove('salmonella'); print(things) surprise = ['Groucho', 'Chico', 'Harpo']; for word in surprise: print(word, 'lower, reverse, capitalize = ', word.lower(), word.swapcase(), word.capitalize()) e2f = { "dog":"chien", "cat":"chat", "walrus": "morse" }; print("e2f, walrus = ", e2f['walrus']); key = e2f.keys(); val = e2f.values(); print("key = ", key) print("val = ", val) l = [item for item in zip(val, key)] print(l) f2e = dict([item for item in zip(val, key)]) print(f2e) print(f2e['chien']) english_words = { word for word in e2f.keys()} print("english_words = ", english_words) life = { "animals" : { "cats": ["Henri", "grumpy", "Lucy"], "octopi": {}, "emus": {} }, "plants": {} , "other" : {} } print("life.keys() = ", list(life.keys())) print("animals = ", life['animals']) print("animals-> cats", life['animals']['cats'])
#!/usr/bin/env python3 import random import time def quicksort(ary): print(ary) if len(ary) <= 1: return ary pivot = ary[len(ary)//2] _l = [x for x in ary if x < pivot ] _m = [x for x in ary if x == pivot ] _r = [x for x in ary if x > pivot ] return quicksort(_l) + _m + quicksort(_r) def main(): random.seed(int(time.time())) print(quicksort([random.randint(1, 100) for x in range(20)])) if __name__ == '__main__': main()
# # This file contains the Python code from Program 7.9 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm07_09.txt # class OrderedListAsArray(OrderedList): class Cursor(Cursor): def insertAfter(self, obj): if self._offset < 0 \ or self._offset >= self._list._count: raise IndexError if self._list._count == len(self._list._array): raise ContainerFull insertPosition = self._offset + 1 i = self._list._count while i > insertPosition: self._list._array[i] = self._list._array[i - 1] i -= 1 self._list._array[insertPosition] = obj self._list._count += 1 # ... # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def do_test_try_catch(): a = 1 try: print("hello, a") a = 2 return a except: print("catched...") return a -1 else: print("else...") a = 3 finally: print("finally...") a = 10 print("a = {}".format(a)) return a def main(): print(do_test_try_catch()) if __name__ == '__main__': print("test for threading...") main()
# # This file contains the Python code from Program 8.2 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm08_02.txt # class Float(float, Object): def __hash__(self): (m, e) = math.frexp(self) mprime = int((abs(m) - 0.5) * (1L << 52)) return mprime >> 20 # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys, math, random from datetime import datetime, date, time import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600,500)) font1 = pygame.font.Font(None, 30) pos_x = 300 pos_y = 250 white = 255,255,255 blue = 0,0,255 black = 0,0,0 red = 255, 0, 0 red1 = 128, 0, 0 c_hour = 0, 210, 230 c_min = 150, 0, 133 c_sec = 100, 111, 0 pygame.display.set_caption("Drawing Circles") radius = 200 angle = 360 def print_text(font, x, y, text, color=(255, 255, 255)): screen.blit(font.render(text, True, color), (x, y)) def draw_numbers(): for degress in range(30, 361, 30): angle = math.radians(degress - 90) x = math.cos( angle ) * (radius - 20) - 10 y = math.sin( angle ) * (radius - 20) - 10 print_text(font1, x + pos_x, pos_y + y, str(degress//30), red1) def draw_time(): today = datetime.today() # draw hour hours = today.hour % 12 angle = math.radians( hours * 360 / 12 - 90) x = math.cos(angle) * (radius - 80) y = math.sin(angle) * (radius - 80) pos = (pos_x + x, pos_y + y) pygame.draw.line(screen, c_hour, (pos_x, pos_y), pos, 25) # draw minute minute = today.minute angle = math.radians ( minute * 360 / 60 - 90) x = math.cos(angle) * (radius - 60) y = math.sin(angle) * (radius - 60) pos = (pos_x + x, pos_y + y) pygame.draw.line(screen, c_min, (pos_x, pos_y), pos, 15) # draw second second = today.second angle = math.radians ( second * 360 / 60 - 90) x = math.cos(angle) * (radius - 40) y = math.sin(angle) * (radius - 40) pos = (pos_x + x, pos_y + y) pygame.draw.line(screen, c_sec, (pos_x, pos_y), pos, 6) print_text(font1, 0, 0, "{0:02d}:{1:02d}:{2:02d}".format(hours, minute, second)) def draw_center(): pygame.draw.circle(screen, white, (pos_x, pos_y), 20) #def draw_numbers(): # # angle = 420 # step = -30 # # for num in range(1, 13): # # x = math.cos( math.radians(angle) ) * (radius - 20) - 10 # y = math.sin( math.radians(angle) ) * (radius - 20) + 10 # # angle += step # # print_text(font1, x + pos_x, pos_y - y, str(num), red1) #def draw_numbers(): # for n in range(1, 13): # angle = math.radians( n * (360/ 12) - 90) # x = math.cos( angle ) * (radius - 20) - 10 # y = math.sin( angle ) * (radius - 20) - 10 # print_text(font1, x + pos_x, y + pos_y, str(n), red1) while True: for evt in pygame.event.get(): if evt.type == QUIT: sys.exit() keys = pygame.key.get_pressed() if keys[K_ESCAPE]: sys.exit() screen.fill(black) #angle += 1 #if angle >= 360: # angle = 0 # color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # # #x = math.cos( math.radians(angle) ) * radius #y = math.sin( math.radians(angle) ) * radius pygame.draw.circle(screen, red, (pos_x, pos_y), radius, 6) draw_numbers() draw_time() draw_center() pygame.display.update()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ep import timeit from ep import show_item_info import sys def _index_words(text): result = [] if text: result.append(0) for index, l in enumerate(text): if l == ' ': result.append(index + 1) return result @show_item_info @timeit def _main(): text = "Four score and seven years ago..." res = _index_words(text) print(res) if __name__ == '__main__': _main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class OnlyOne: class __OnlyOne: def __init__(self): self.val = None def __str__(self): return repr(self) + self.val instance = None def __new__(cls): if not OnlyOne.instance: OnlyOne.instance = OnlyOne.__OnlyOne() return OnlyOne.instance def __getattr__(self, name): return getattr(OnlyOne.instance, name) def __setattr__(self, name, val): return setattr(OnlyOne.instance, name, val) if __name__ == '__main__': print("test for new singleton") a = OnlyOne() a.val = "aaa" print(a) b = OnlyOne() c = OnlyOne() b.val = "bbb" print(a) print(b) print(c)
# 2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # What is the sum of the digits of the number 2^(1000)? # LOGIC # left shift of 1 is powering by 2, then add the digits (count, n) = (0, 1 << 1000) while (n >= 1): count += n % 10 n /= 10 print count
# You are given the following information, but you may prefer to do some research for yourself. # * 1 Jan 1900 was a Monday. # * Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # * A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? # LOGIC: # Find out the start day for each Year. Now given the start day and the year, we can find the start day of each month week_days = {0 : 'Sun', 1 : 'Mon', 2 : 'Tue', 3 : 'Wed', 4 : 'Thu', 5 : 'Fri', 6 : 'Sat'} def leapYear(year): if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True else: return False def daysInYear(year): if leapYear(year): return 366 return 365 def daysInMonth(year): days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if leapYear(year): days[1] = 29 return days return days def sunsOnFirst(start_day, year): days = daysInMonth(year) no_of_fst_suns = 0 for day in range(len(days)): if start_day == 0: no_of_fst_suns += 1 end_day = days[day] % 7 start_day = (end_day + start_day) % 7 return no_of_fst_suns ## No use of this function, I read the question wrongly def noOfSuns(start_day): no_suns = 0 ## I know there are 31 days in Jan no_of_weeks = 31 / 7 no_suns += no_of_weeks ## 31 % 7 = 3 ## so if it starts on Sunday, then +2 including Sunday will include Monday if start_day == 0 or ((start_day + 2) % 7 < start_day and (start_day + 2) % 7 >= 0): no_suns += 1 return no_suns if __name__ == '__main__': ## 8th day will be the same day ## we know it started on Monday, so next start day of the year will be 1 + next suns_on_first = 0 start_day = 1 for year in range(1901, 2001): ## - 1 because we are finding the start date and start date depends on the nomber of days in ## prev year end_day = daysInYear(year - 1) % 7 start_day = (end_day + start_day) % 7 suns_on_first_this_yr = sunsOnFirst(start_day, year) suns_on_first += suns_on_first_this_yr print week_days[start_day], "is the start day of", year, "and has", suns_on_first_this_yr, "Sundays on 1st" print "Number of Suns of 1st", suns_on_first
# Take the number 192 and multiply it by each of 1, 2, and 3: # 192 x 1 = 192 # 192 x 2 = 384 # 192 x 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) # The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). # What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? # LOGIC: # Brute force with better boundaries. # Cases: # 1. Multiplicand starts with 1 and is sequential # 2. Total length of concatenated products == 9 # Iterate till we have cat(prod) > 9 and store if isPandigital def isPandigital(num): """ use count sort to arrange since i know the input set and if there is a 'hole' or if there is a 'hit' (same number repeats) then fail """ count_sort = [0,0,0,0,0,0,0,0,0,0] count = 0 while(num >= 1): rem = num % 10 ## pandigital from 1 to 9 (not 0) if rem == 0: return False try: ## is it same number again? if count_sort[rem] == 0: count_sort[rem] = rem else: return False except: return False num /= 10 count += 1 ## did i over shoot? if count == 9: return True return False if __name__ == '__main__': count = 2 pand = [] while True: flag = -9 prod = '' for i in range(1,10): res = str(i * count) flag = i ## attach to prod only if len of prod < 9 if (len(prod) + len(res) > 9): break else: prod += res if (isPandigital(int(prod))): print prod, i, count pand.append(prod) ## questions says n > 1 if flag == 2: break count += 1 print max(pand)
def delete_letters(letter, text): up_letter = str.upper(letter) low_letter = str.lower(letter) change_text = "" str(change_text) str(text) for i in text: if i != low_letter and i != up_letter: change_text += i return change_text print(delete_letters("a", "Bartosz"))
#!/usr/bin/python3 import sys if __name__ == '__main__': """Prints the argument list passed to the program The program takes all the arguments starting from the second and prints the number of arguments and their value """ av = sys.argv l_av = len(av) - 1 if l_av > 1: print(l_av, 'arguments:') for i in range(1, l_av + 1): print('{:d}: {}'.format(i, av[i])) elif l_av == 1: print(l_av, 'argument:') for i in range(1, l_av + 1): print('{:d}: {}'.format(i, av[i])) elif l_av == 0: print(l_av, 'arguments.')
#!/usr/bin/python3 """ A integer validator module """ class BaseGeometry: """ A super class to implements geometrical shapes """ def area(self): """ Raises an exception when you call this function """ raise Exception('area() is not implemented') def integer_validator(self, name, value): """ Checks a integer value Args: name (str): The name of the value. value (int): The value. Raises: TypeError: If `value` isn't a integer. ValueError: If `value` is less than or equal to zero. """ if type(value) is not int: raise TypeError(name + ' must be an integer') if value <= 0: raise ValueError(name + ' must be greater than 0')