text
stringlengths
37
1.41M
#%% # Open the flat txt file (text of moby dick novel) # Remember the process of open and close file file = open("moby_dick.txt", mode = 'r') # Print file print(file.read()) # Check whether file is closed print(file.closed) # close file file.close() # Check again whether file is closed print(file.closed) #%% # Import text files line by line # Want to print the first few lines # Concept of CONTEXT MANAGER: bind a variable 'file' by using context manager # structure as with ... as ... # the variable will be bound to function after with... with open('moby_dick.txt', mode = 'r') as file: print(file.readline()) print(file.readline()) print(file.readline()) # %% # Import file MNIST.csv to numpy array import numpy as np import ast import matplotlib.pyplot as plt file1 = open('digits_MNIST_list.csv') digits_MNIST = file1.read() digits_MNIST1 = digits_MNIST.replace("'","") digits = ast.literal_eval(''.join(digits_MNIST1)) digits_np = np.array(digits) print(digits_np) # appropriate method for convert list to numpy array # Select and reshape a row im = digits_np[21, 1:] im_sq = np.reshape(im, (28,28)) # Plot reshaped data (matplotlib.pyplot required) plt.imshow(im_sq, cmap='Greys', interpolation='nearest') plt.show() # %% # Import file digits.csv as datacamp import numpy as np import matplotlib.pyplot as plt # Assign filename to variable: file file = 'digits.csv' # Load file as array: digits digits = np.loadtxt(file, delimiter=',') print(type(digits)) # Select and reshape a row im = digits[21, 1:] im_sq = np.reshape(im, (28,28)) # Plot reshaped data (matplotlib.pyplot required) plt.imshow(im_sq, cmap='Greys', interpolation='nearest') plt.show() # %% # For case has header (not need to import), delimiter not ',' could be '\t' for tab # 'skiprows': allows to specify how many rows(not indices) wish to skip # 'usecols' takes a list of the indices of the columns wish to keep # np.loadtxt(): importing is tab-delimited, skip the first row, # import only the first and third columns import numpy as np # Assign the filename: file file = 'digits_header.txt' # Load the data: data data = np.loadtxt(file, delimiter='\t', skiprows=1, usecols=(0,2)) print(data) # %% # Using file seaslug.txt # has a text header, consisting of strings # is tab-delimited # Try to import it as-is using np.loadtxt() --> ValueError as "could not convert string to float" # 2 solutions: # 1. set the data type argument dtype = str(for string) # 2. skip the first rows as skiprows #%% # use 1st method import numpy as np import matplotlib.pyplot as plt file = 'seaslug.txt' data = np.loadtxt(file,delimiter='\t', dtype=str) # Print the first element of data print(data[0]) # Plot a scatterplot of data plt.scatter(data[:,0], data[:,1]) plt.xlabel('time (min.)') plt.ylabel('percentage of larvae') plt.show() # %% # Second method import numpy as np import matplotlib.pyplot as plt file = 'seaslug.txt' data_float = np.loadtxt(file, delimiter='\t', dtype=float, skiprows=1) # Print the 10th element of data_float print(data[9]) # Plot a scatterplot of the data plt.scatter(data_float[:,0], data_float[:,1]) plt.xlabel('time (min.)') plt.ylabel('percentage of larvae') plt.show() # %% # Working with mixed datatypes(1) # datasets with various datatypes in different columns (string, float, etc) # - np.loadtxt() will freak out # - np.genfromtxt() can handle such structures, pass 'dtype=None' will figure # out what types each column should be # Using titanic.csv for example: # + delimiter = , # + argument 'names': True=header, False=no header # Because the datatype are of different types, 'data' is an object called # a "structured array" # Because numpy array have to contain elements that are all the same type, # the structure array solves this by being a 1D array, where each element of # the array is a row of the flat file imported. # import the titanic file file = 'titanic.csv' import numpy as np # import data by genfromtxt data = np.genfromtxt(file,delimiter=',', names=True, dtype=None) # print out the first 5 line of data, to get the ith row --> data[i] print(data[0:5]) # Print out the column with name --> data['name'], print out the data of column 'Fare', 'Survived' # Print out the last 4 values of 'survived' column print(data['Survived'][-5:-1]) print(data['Survived']) # Print out first 3 entries of data print(data[:3]) # %% # Another function is 'np.recfromcsv()' behaves similarly to # 'np.genfromtxt()', except that its default: # delimiter=',' # names=True # dtype=None # Using the function for 'titanic.csv' file, print the first 3 # entries of the data file = 'titanic.csv' data = np.recfromcsv(file) print(data[:3]) # %%
#%% # Define function plot_pop() which takes 2 arguments: # 1. The filename of the file to be processed # 2. the country code of the rows to process in dataset # The function will do: # - Loading of the file chunk by chunk # - Creating the new column of urban population values # - Plot the urban population data # %% # Import pandas and matplotlib import pandas as pd import matplotlib.pyplot as plt # Create function plot_pop() def plot_pop(filename,country_code): # Loading file to chunk by chunk world_bank = pd.read_csv(filename,chunksize=1000) # Create empty DataFrame: data data = pd.DataFrame() # Iterate over each dataframe chunk for df_urb_pop in world_bank: # select the CountryCode df_urb_code = df_urb_pop[df_urb_pop['CountryCode'] == country_code] # zip two column 'Total Population' and 'Urban poplulation (% of total)' pops = zip(df_urb_code['Total Population'], df_urb_code['Urban population (% of total)']) # change zip to list pops_list = list(pops) # Add new column to df_urb_pop: total_urban_population, using list comprehesion df_urb_code['Total urban population'] = [int(num[0]*num[1]*0.01) for num in pops_list] # Append DataFrame chunk to data: data data = data.append(df_urb_code) data.plot(kind='scatter',x='Year', y='Total urban population') plt.show() fn = 'world_ind_pop_data.csv' plot_pop(fn,'CEB') plot_pop(fn,'ARB') # %%
#%% # toss game: 1 - tail, 0 for head import numpy as np import matplotlib.pyplot as plt np.random.seed(123) final_tails = [] #show numbers of tails for each 10 times tosses # do the work 100 times of toss x times for x in range(10000): tails = [0] # toss 10 times for x in range(10): coin = np.random.randint(0,2) tails.append(tails[x] + coin) final_tails.append(tails[-1]) # add the final toss count print(final_tails) plt.hist(final_tails, bins = 10) plt.show() # %%
# IMPORT FLAT FILES USING PANDAS # 1. What a data scientist needs? # - Two dimensional labeled data structure(s) # - Columns of potentially different types # - Manipulate, slice, reshape, groupby, join, merge # - Perform statistics # - Work with time series data # DataFrames are observations and variables # 2. Manipulating pandas DataFrames # - Exploratory data analysis # - Data wrangling # - Data reprocessing # - Building models # - Visualization # 3. Importing using pandas # - using pd.read_csv # - sep = delimiter in numpy # - comment='#' # - na_values = takes a list of strings to recognize as NA/NaN # - data.head() --> check the first 5 rows of the dataframe, # including the header # 4. Easily convert dataframe to numpy array by: data.values #%% # Using titanic.csv file import pandas as pd file = 'titanic.csv' # Assign file name: file file = pd.read_csv(file) # View the head of the DataFrame print(file.head()) # %% # Using pd.values to convert dataframe to numpy array # Using 'digits.csv' file import pandas as pd file = 'digits.csv' data = pd.read_csv(file, nrows=5, header=None) # Convert to numpy array data_array = data.values # Print out type of data_array print(type(data_array)) # %% # DEAL WITH FILE CONTAINED COMMENTS(#), MISSING VALUE (NA, NaN) # Using 'titanic_corrupt.txt' # sep='\t', comment='#', na_values='Nothing' import pandas as pd import matplotlib.pyplot as plt file = 'titanic_corrupt.txt' # Import file: data data = pd.read_csv(file, sep='\t', comment='#', na_values='Nothing') # for comment to remove any comment in data # # Print the head of the DataFrame print(data.head()) # Plot 'Age' variable in a histogram pd.DataFrame.hist(data[['Age']]) plt.xlabel('Age (years)') plt.ylabel('count') plt.show() # %% # Can change to numpy array but just good for all number than mixed data data_array = data.values print(data_array[2:5]) # %%
import sys import operator my_operators = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "\\": operator.truediv, ":": operator.truediv } def calculator(x,y,z): try: return y(int(x),int(z)) except ZeroDivisionError: return "Division by zero." def is_int(x): try: int(x) return True except ValueError: return False def bold(text): return "\033[1m" + text + "\033[0;0m" while True: n1 = input("Enter a number (or a letter to " + bold("exit") + "): ") if not is_int(n1): break while True: op = input("Enter an operation: ") if op in my_operators.keys(): break print("Try again, not a valid operator: " + ", ".join(o for o in my_operators.keys())) while True: n2 = input("Enter another number: ") if is_int(n2): break print("Try again, not a valid integer.") result = calculator(n1, my_operators[op], n2) print ("Result: " + str(result), end="") print ("\n") print("Bye!")
# Given a non-empty array of integers, every element appears twice except for one. Find that single one. # # Note: # # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? class Solution: def singleNumber(self, nums): for i in range(1, len(nums)): nums[0] ^= nums[i] return nums[0] def run(): nums= [4,1,2,1,2] solver = Solution() print(solver.singleNumber(nums)) if __name__=="__main__": run()
# Populating Next Right Pointers in Each Node # Solution # You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: # # struct Node { # int val; # Node *left; # Node *right; # Node *next; # } # Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. # # Initially, all next pointers are set to NULL. """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution(): def connect(self, root): def dfs(node): if not node: return if root.left and root.right: root.left.next = root.right if root.right and root.next: root.right.next = root.next.left dfs(node.left) dfs(node.right) dfs(root) return root class Solution_bfs: def connect(self, root: 'Node') -> 'Node': if not root:return tmp = [root] while len(tmp)>0: new_tmp = [] for i in range(len(tmp)): if i + 1< len(tmp): tmp[i].next = tmp[i+1] if tmp[i].left: new_tmp.append(tmp[i].left) if tmp[i].right: new_tmp.append(tmp[i].right) tmp = new_tmp return root
class Solution(): def bigger_left(self, nums): stack = [] new_list = nums[::-1] print('nums:', nums) print('nes_list:', new_list) res = [0] * len(nums) for i in range(len(nums)): while stack and new_list[stack[-1]] < new_list[i]: temp = stack.pop() res[temp] = new_list[i] stack.append(i) return res[::-1] if __name__ =="__main__": test_list = [73, 74, 75, 71, 69, 72, 76, 73] solver = Solution() print(solver.bigger_left(test_list))
# # Daily Temperatures # Solution # Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days # you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. # # For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be # [1, 1, 4, 2, 1, 1, 0, 0]. # # Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer # in the range [30, 100]. class Solution(): def dailyTemperature(self, T): ans = [0]*len(T) stack = [] for i in range(len(T)): while stack and T[stack[-1]] < T[i]: cur_ind = stack.pop() ans[cur_ind] = i - cur_ind stack.append(i) return ans if __name__ =="__main__": test_list = [73, 74, 75, 71, 69, 72, 76, 73] solver = Solution() print(solver.dailyTemperature(test_list))
# Target Sum # Solution # You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. # # Find out how many ways to assign symbols to make sum of integers equal to target S. # # Example 1: # Input: nums is [1, 1, 1, 1, 1], S is 3. # Output: 5 # Explanation: # # -1+1+1+1+1 = 3 # +1-1+1+1+1 = 3 # +1+1-1+1+1 = 3 # +1+1+1-1+1 = 3 # +1+1+1+1-1 = 3 # # There are 5 ways to assign symbols to make the sum of nums be target 3. class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: """ :type nums: List[int] :type S: int :rtype: int """ # _len = len(nums) # dp = [collections.defaultdict(int) for _ in range(_len + 1)] # dp[0][0] = 1 # for i, num in enumerate(nums): # for sum, cnt in dp[i].items(): # dp[i + 1][sum + num] += cnt # dp[i + 1][sum - num] += cnt # return dp[_len][S] _len = len(nums) dp = [collections.defaultdict(int) for _ in range(_len + 1)] dp[0][0] = 1 for i, num in enumerate(nums): for sum,cnt in dp[i].items: dp[i+1][sum + num] += cnt dp[i+1][sum - num] += cnt return dp[_len][S]
from binarytree import Node root = Node(3) root.left = Node(6) root.right = Node(8) # Getting binary tree print('Binary tree :', root) # Getting list of nodes print('List of nodes :', list(root)) # Getting inorder of nodes print('Inorder of nodes :', root.inorder) # Checking tree properties print('Size of tree :', root.size) print('Height of tree :', root.height) # Get all properties at once print('Properties of tree : \n', root.properties)
#string functions def starts(sentence): if sentence.startswith("M"): print("the given sentence starts with H") else: print("the given sentence doesn't start with H") print(starts("Mad titan"))
def generalTuple(): # general tuple - 1 emptyTuple = () print(emptyTuple) numbersTuple = (1, 2, 3, 4, 5) print(numbersTuple) stringTuple = ('IND', 'AUS', 'KOR') print(stringTuple) generalTuple()
# list for loop def reverseList(my_list): my_list.reverse() return my_list my_list = ['♾Infinity', 'knew', 'who', 'man', 'The'] print(reverseList(my_list)) for i in my_list: print(i)
def dictionary9(): employee_dict = { 'name': 'sam', 'company': 'abc', 'role': 'software architect', } # using len() print(len(employee_dict)) # using keys() keyCounter = 0 for key, value in employee_dict.items(): print(key + ':', value) keyCounter = keyCounter + 1 return keyCounter print(dictionary9())
def indexing(my_list): firstItem = my_list[0] lastItem = my_list[len(my_list) - 1] negativeIndexing = my_list[-2] # normal copy my_list_copy = my_list print(my_list_copy) # using copy method my_list_copy2 = my_list.copy() print(my_list_copy2) slicing = my_list[0:4] return [firstItem,lastItem,negativeIndexing,slicing] print(indexing([1,2,3,4,5]))
def colours(color1, color2, color3): return color1 + ' ' + color2 + ' ' + color3 print(colours(color1='red',color2='blue',color3='green'))
# list concatenate , repeat, length def opertorsList(list1, list2): concatenation = list1 + list2 repeat = list1 * 3 return [concatenation, repeat] print(opertorsList([1, 2, 3], ['what', 'was', 'it ?'])) print(len([5,3,3,2,1]))
# default arguments def default(name, age): print("Hello {}, and my age is {}.".format(name, age)) print(default("i am sarath",21))
# pop(), del, remove(), clear() def deletions(my_list): #my_list without any operations on it print(my_list) # deleting last element using pop() my_list.pop() print(my_list) # deleting element based on index my_list.pop(1) print(my_list) # using del keyword to delete based on index del my_list[2] print(my_list) # using remove() method to delete an element my_list.remove('4') print(my_list) # using clear() method to empty the list my_list.clear() print(my_list) # using del keyword to delete the entire list del my_list # print(my_list) deletions([9,'2','4','5','40'])
height = float(input("Your height in metres:")) weight = float(input("Your weight in kilograms:")) bmi = round(weight/ (height * height), 1) if bmi <= 18.5: print('Your BMI is', bmi, 'which means you are underweight.') elif bmi > 18.5 and bmi < 25: print('Your BMI is', bmi, 'which means you are normal.') elif bmi > 25 and bmi < 30: print('Your BMI is', bmi, 'which means you are overweight.') elif bmi > 30: print('Your BMI is', bmi, 'which means you are obese.') else: print('There is an error with your input')
n1=99 n2=7 n3=15 if (n1>n2) and (n1>n3): largest=n1 elif (n2>n1) and (n2>n3): largest=n2 else: largest=n3 print("Largest between 3 numbers is",largest)
''' if condition1: statement1 elif condition2: statement2 else: statement3 ''' #%% print('case1') x = 1 y = 2 if x > y: print('x is greater than y') else: print('x is less or equal to y') print() print('case2') x = 1 y = 1 if x > y: print('x is greater than y') elif x < y: print('x is less than y') else: print('x is equal to y') print() print('case3') N = 7 if N < 7: print("N<7") elif N == 7: print("N=7") elif N >= 7: print('N>=7') print() print('case4') N = 7 if N < 7: print("N<7") if N == 7: print("N=7") if N >= 7: print("N>=7") print() print("inline if else") x = 1 y = 2 z = x if x > y else y print(z) # %%
############################################################## # Project 6: Numeric Computations with Taylor Polynomials # # # # Logan Hoots, Stephen Sanders # # CST - 305 # # 5/6/2020 # # Professor R. Citro # ############################################################## # Imports all necessary libraries for the project import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt import matplotlib.pyplot as plt_ import math from sympy import * # Main function in which the general solution is calculated def model_(input_): # Defines the first two values of a_0 and a_1, allowing the fist values to be calcuated into a_0 and a_1x a = [1, 1] # Declaring i as a float in order to get nonzero numbers i = 0.0 # Iterates the amount of times the user inputs for x in range(0, input_ - 1): # Appends every new value into the array for every given iteration a.append(round((i**2 - i + 1) / (4 *(i + 2) * (i + 1 )) * a[x], 4)) i += 1 print("\nGENERAL SOLUTION: \n") print("y = "), # Prints out the first two cases of a_0 and a_1 # Handles the coordinating association between a_0 and a_1 for x in range(0, len(a)): if (x == 0): print("a_0 +"), elif (x == 1): print("a_1x +"), elif (x % 2) == 0: print(str(a[x]) + " * a_0x^" + str(x) + " +"), elif (x % 2) != 0: print(str(a[x]) + " * a_1x^" + str(x) + " +"), print("...") print("\nGENERAL SOLUTION SIMPLIFIED: ") # Prints the simplified general solution print("\ny = a_0 ("), for x in range(0, len(a)): if (x % 2) == 0: print(str(a[x]) + "x^" + str(x) + " +"), # Prints the simplified general solution print("...) + a_1 ("), for x in range(0, len(a)): if (x % 2) != 0: print(str(a[x]) + "x^" + str(x) + " +"), print("...)") # Calls the main function model_(input("enter n value:" )) print("\n")
from collections import deque is_balanced = True string = input() stack_of_opening = [] stack_of_closing = deque() for item in string: if item in ["{","(","["]: stack_of_opening.append(item) else: stack_of_closing.append(item) if len(stack_of_closing) == len(stack_of_opening): while stack_of_closing: closing_one = stack_of_closing.popleft() opening_one = stack_of_opening.pop() if closing_one == ")" and opening_one != "(": is_balanced = False elif closing_one == "]" and opening_one != "[": is_balanced = False elif closing_one == "}" and opening_one != "{": is_balanced = False else: is_balanced = False if is_balanced: print("YES") else: print("NO")
from collections import deque firework_effects = deque([int(el) for el in input().split(", ") if int(el) > 0]) explosive_powers = [int(num) for num in input().split(", ") if int(num) > 0] palms = 0 willows = 0 crossettes = 0 ready_with_fireworks = False while not ready_with_fireworks: if not firework_effects or not explosive_powers: break current_firework = firework_effects.popleft() current_power = explosive_powers.pop() sum = current_power + current_firework if sum % 3 == 0 and sum % 5 == 0: crossettes += 1 elif sum % 3 == 0: palms += 1 elif sum % 5 == 0: willows += 1 elif not sum % 3 == 0 and not sum % 5 == 0: current_firework -= 1 firework_effects.append(current_firework) explosive_powers.insert(0,current_power) if crossettes == 3 and willows == 3 and palms == 3: ready_with_fireworks = True if ready_with_fireworks: print(f"Congrats! You made the perfect firework show!") else: print(f"Sorry. You can't make the perfect firework show.") print(f"Firework Effects left: {firework_effects}") print(f" Explosive Power left: {explosive_powers}") print(palms) print(willows) print(crossettes)
rows, cols = [int(el) for el in input().split()] matrix = [] for row in range(rows): matrix.append(input().split()) counter = 0 for r in range(rows-1): for c in range(cols-1): if matrix[r][c] == matrix[r][c+1] and matrix[r][c+1] == matrix[r+1][c] and matrix[r+1][c] == matrix[r+1][c+1]: counter += 1 print(counter)
countries, capitals = input().split(", "), input().split(", ") corresponding_info = zip(countries,capitals) info = {key:value for key,value in corresponding_info} for pair in info.items(): print(f"{pair[0]} -> {pair[1]}")
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD)# set de modes van pin nummering GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)#dit zet pin 11 op als input met een interne pulldown circuit GPIO.setup(12, GPIO.OUT)# dit zet pin 12 als output, hier zit de LED op GPIO.output(12, 0) try: while True: GPIO.output(12, GPIO.input(11))#LED gaat aan als de knop in gedrukt wordt except KeyboardInterrupt: GPIO.cleanup()
>>> a=input("Enter the value ") Enter the value "My Testing String" >>> a.count(' ') 2
def read_file(filename): f = open(filename) input = f.read() f.close() return input if __name__ == "__main__": filename = 'input' input = read_file(filename) pt = 0 for i in input: #print("this char: {}".format(i)) if i == ')': pt -= 1 elif i == '(': pt += 1 print("Final floor: {}".format(pt))
""" Problem 6a - 2019 """ import sys import orbit def traverse(planetary_system, key): """ Recursive function for traversing the planatary system """ orbits = 1 if planetary_system[key] != "COM": orbits += traverse(planetary_system, planetary_system[key]) return orbits def create_planetary_system(data): """ Create dict to represent the planetary system """ planetary_system = dict() for data in data_array: print(data) [base, orbit] = data.split(')') planetary_system[orbit] = base return planetary_system # Init FILE_NAME = "./2019/dec_06/input_ex" if len(sys.argv) > 1: FILE_NAME = sys.argv[1] print("file_name: {}".format(FILE_NAME)) # Read file and extract data file = open(FILE_NAME) file_content = file.read() data_array = [line for line in file_content.split("\n") if line.strip() != ""] planetary_system = create_planetary_system(data_array) print("Planatary system: {}".format(planetary_system)) orbits = 0 for key in planetary_system: orbits += traverse(planetary_system, key) print("Key: {}, orbits: {}".format(key, orbits)) print("indirect orbits: {}".format(orbits))
import re def read_file(filename): data = [] f = open(filename) for line in f: data.append(line) f.close() return data def count_hex(line): p = re.compile(r'\\x[0-9,a-f,A-F][0-9,a-f,A-F]') a = p.findall(line) return(len(a)) def count_chars(line): c = line.count("\"") + line.count("\\\\") + count_hex(line) * 3 return c def main(filename): data = read_file(filename) total_count = 0 for d in data: nbr_chars = count_chars(d) print(d, end='') print(nbr_chars) total_count += nbr_chars print("Total count: {total_count}".format(total_count=total_count)) if __name__ == "__main__": main("input")
"""This is a Python file""" input_file = open('./2019/dec_02/input') line = input_file.read() input_array = line.split(',') input_array[1] = 12 input_array[2] = 2 #print(input_array) PC = 0 while int(input_array[PC]) != 99: #print("PC: {}, op: {}, {} +* {} => {}".format(PC, input_array[PC], input_array[PC+1], #input_array[PC+2], input_array[PC+3])) if int(input_array[PC]) == 1: input_array[int(input_array[PC+3])] = int(input_array[int(input_array[PC+1])]) + \ int(input_array[int(input_array[PC+2])]) #print('add, s: {}'.format(input_array[PC+3])) elif int(input_array[PC]) == 2: input_array[int(input_array[PC+3])] = int(input_array[int(input_array[PC+1])]) * \ int(input_array[int(input_array[PC+2])]) else: print('Wrong OP code {}'.format(input_array[PC])) exit() PC += 4 #print(input_array) #print(input_array) print("answer is: {}".format(input_array[0]))
number = [] print("enter 8 number : ") for i in range(8): number.append(int(input())) largest = number[0] for i in range(8): if largest < number[i]: largest = number[i] secondLargest = number[0] for i in range(8): if secondLargest < number[i]: if number[i] != largest: secondLargest = number[i] print("\n Second Largest Number is: ", end=" ") print(secondLargest)
x=int(input("Enter the Year")) result= "Leap Year" if x%400==0: print(result) elif x % 4 == 0 and x % 100 != 0: print(result) else: print("non leap year")
# def whiletest(testvalue): # numbers = [] # i = 0 # while i < testvalue: # print "At the top i is %d" % i # numbers.append(i) # # i = i + 2 # print "Numbers now: ", numbers # print "At the bottom i is %d\n" % i # return numbers def whiletest(testvalue): numbers = [] for num in testvalue: numbers.append(num) return numbers numbers = whiletest(range(0,10)) print "The numbers: " for num in numbers: print num
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x<0 or (x%10==0 and x!=0): return False reverse=0 while x>reverse: reverse=10*reverse+x%10 x=x//10 if x==reverse or x==reverse//10: return True else: return False """ Runtime: 284 ms, faster than 71.74% of Python3 online submissions for Palindrome Number. point:the reverse algorithm ignores zeros in the end of a number 1700 will be reverse as 71, so 12100 will be cut like 1 and 21, which need to preset an if to exclude such situation on the other hand, choosing to just reverse half of the number does not lead to obvious less time. """
print("please input a list of numbers") L = list(input().split()) print(L) print(L.__len__()) l = [int(i) for i in L] print(l) print("please input the value you want to search") value = input() value = int(value) if not l: print("no value in list") low = 0 high = len(l) - 1 while low <=high: mid = int((low + high) / 2) if value == l[mid]: print("{} is the {}th number in the list" .format(value, mid+1)) exit() elif value > l[mid] and: if l[mid] > l[high]: low = mid + 1 else: if value > l[high]: high = mid - 1 else: low = mid + 1 elif value < l[mid]: if l[mid] < l[high]: high = mid - 1 else: if value < l[low]: low = mid + 1 else: high = mid - 1 print("not found")
class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ low=int(0) high=x while low<=high: mid=low+(high-low)//2 if mid*mid<=x: low=mid+1 else: high=mid-1 return high """ first i use (low+high)//2 Runtime: 64 ms,faster than 67.46% of Python3 online submissions for Sqrt(x). also binary search but when i change (high+low)//2 to low+(high-low)//2, suddenly Runtime: 56 ms, faster than 91.95% of Python3 online submissions for Sqrt(x). this is because plus result much bigger number and more time for division calculation. keep it in mind! """
from random import randrange as r def thirtyOne(): #deciding who the hell starts play = input("Input 1 to jugar, anycosa else to safar de aqui.") while play=="1": counter = 0 playsUser = True if r(2) == 1 else False #only r(2) is needed in fact print(("Player" if playsUser else "Computer")+" goes first!") #running game while counter < 31: numbers = 0 if playsUser: numbers = input("Please input integer numbers between 1 to 3: ") while numbers not in ["1","2","3"]: numbers = input("Goddammit. I said integer numbers between 1 to 3: ") numbers = int(numbers) print("your call is: ",end="") else: if counter < 27: numbers = r(3) + 1 elif counter < 30: numbers = 30 - counter else: numbers = 1 print("computer calls: ",end="") # increasing counter print(' '.join([str(i) for i in range(counter+1,counter+1+numbers)])) counter += numbers # switching player playsUser = not playsUser print(("Player" if playsUser else "Computer")+" wins! :'v") play = input("Input 1 to jugar, anycosa else to safar de aqui.") thirtyOne() #[print(r(2)) for i in range(10)]
import sys import operator def define_grid(): grid = [] empty_spaces = list() preset_chars = dict() row = 0 col = 0 start = True with open(sys.argv[1], 'r') as myFile: for line in myFile: col = 0 start2 = True if start == True: start = False else: row +=1 new_row = [] for char in line: if start2 == True: start2 = False else: col +=1 if char == '_': empty_spaces.append([row, col]) new_row.append('_') elif char == '\r' or char == '\n': continue else: preset_chars[(row,col)] = char new_row.append(char) grid.append(new_row) return grid, empty_spaces, preset_chars def word_list(): ret_list = [] with open(sys.argv[2], 'r') as myFile: for line in myFile: temp_line = [] for char in line: if char == '\r' or char == '\n': pass else: temp_line.append(char.upper()) temp = ''.join(temp_line) ret_list.append(temp) return ret_list def main(): """ argv[1] == grid file argv[2] == word bank file argv[3] == steps to solution argv[4] == solution file """ myGrid, empty_chars, preset_chars = define_grid() myWordList = word_list() word_dict = {} for elem in myWordList: word_dict[elem] = [] for i in range(0, 8): for j in range(0, 8): start_coordinates = (i, j) # check vertical placement vertical_fit = True b = j for letter in elem: if b <= 8: if myGrid[i][b] == '_' or myGrid == letter: b += 1 else: vertical_fit = False # we know the entire word wont fit for this particular start coordinate break # if the word does fit, add the start coordinate to the domain if vertical_fit: word_dict[elem].append((start_coordinates, 'V')) # check horizontal placement horizontal_fit = True a = i for letter in elem: if a <= 8: if myGrid[a][j] == '_' or myGrid == elem[0]: a += 1 else: horizontal_fit = False # we know the entire word wont fit for this particular start coordinate break # if the word does fit, add the start coordinate to the domain if horizontal_fit: word_dict[elem].append((start_coordinates, 'H')) for elem in word_dict: print("WORD: " + elem + ", DOMAIN: " + str(word_dict[elem]) + ", DOMAIN_LENGTH: " + str(len(word_dict[elem]))) sorted_dict = sorted(word_dict, key=lambda k: len(word_dict[k])) for item in sorted_dict: print("WORD: " + item + " LENGTH: " + str(len(word_dict[item]))) # for item in range(0,len(sorted_dict)-1): # print("WORD: " + sorted_dict[item] + ", LENGTH" + str(len(sorted_dict[item]))) #preset_chars = [] # # Find all preset characters # for x in range(0, 8): # for y in range(0, 8): # if grid[x][y] != '_': # preset_chars.append(grid[x][y], 0) # print("BEFORE SORT: " + str(word_dict)) # # for word in word_dict.keys(): # for pair in preset_chars: # letter = preset_chars[pair] # if letter in word: # word_dict[word] += 1 # # post_sort = sorted(word_dict.items(), key=operator.itemgetter(1), reverse=True) # # print("AFTER SORT: " + str(post_sort)) if __name__ == '__main__': main()
# Dependencies import random from math import gcd #Variables with open("./primes.txt", "r") as file: primes = file.readlines() #Functions def define_e(phi_n: int) -> int: while(True): e = random.randint(2, phi_n-1) if(gcd(e, phi_n)==1): return e def define_d(e: int, phi_n: int) -> int: phi_aux = phi_n x, old_x = 0, 1 y, old_y = 1, 0 while(phi_n != 0): quotient = e // phi_n e, phi_n = phi_n, e - quotient * phi_n old_x, x = x, old_x - quotient * x old_y, y = y, old_y - quotient * y return old_x if old_x >= 0 else old_x + phi_aux def generate_new_keys() -> tuple: p: int = int(primes[random.randint(671, len(primes)-1)]) while(True): q = int(primes[random.randint(671, len(primes)-1)]) if(p!=q): break n: int = p * q phi_n: int = (p-1)*(q-1) e: int = define_e(phi_n) public = (e, n) d: int = define_d(e, phi_n) private = (d, n) return public, private def encrypt(message: str, key: list) -> str: try: return "g".join([hex(pow(ord(letter), int(key[0]), int(key[1])))[2:] for letter in message]) except: return "Error!" def decrypt(message: str, key: list) -> str: try: arr: list = message.split("g") message: str = "".join([chr(pow(int(element, 16), int(key[0]), int(key[1]))) for element in arr]) return message except: return "Error!" if __name__ == '__main__': public, private = generate_new_keys() message: str = 'Hello, world! 👋' cifer: str = encrypt(message, public) decipher: str = decrypt(cifer, private) print(cifer, decipher)
import sys import time print("You ready to count? Let's count to 100. It'll go fast, so.. be ready\n") time.sleep(3) i = 0 while i < 100: i += 1 sys.stdout.write("\r{}".format(str(i))) print("\n\nOh, did I go a little too fast for you? Here, lets count to a million.\n") time.sleep(3) i = 0 while i < 1000000: i += 1 sys.stdout.write("\r{}".format(str(i))) print('\n\nWoah! That was a lot. Let\'s try that again sometime!')
def find_mlt_inv(cur_mult="input", mod_max="input"): """ Find the multiplicative inverse of a current multiplier(mod "mod_max") -------------------------------------------------------------------------- Parameters: cur_mult: int The current multiplier mod_max: int The current divisor inside the modulus i.e. 10 + 7(mod 5) where 5 would be mod_max Return: mlt_inv : int The multiplicative inverse of cur_mult(mod_max) """ import numpy as np import easygui if cur_mult == "input": cur_mult = easygui.integerbox("What is the current multiplier you want to get rid of?") if mod_max == "input": mod_max = easygui.integerbox("What is the number in parenthesis after the word \'mod\'?") if type(cur_mult) != int or type(mod_max) != int: print("One of the inputs isn't an interger") print("cur_mult is of type:" + str(type(cur_mult))) print("mod_max is of type:" + str(type(mod_max))) return None mod_max = [i for i in range(mod_max)] mltpls = np.array([]) for i in mod_max: show = i * cur_mult % 26 print(str(i) + " x 7 % 26 = " + str(show)) if show == 1: mlt_inv = i print("The multiplicative inverse is: \t" + str(mlt_inv)) return mlt_inv er_no_inv = "There was no multiplicative inverse found" return er_no_inv class crp: """ An object for handling Cryptography based manipulations -------------------------------------------------------- """ def __init__(self, ctx="", ptx="", nvl_elms=[]): self.cyphertext = ctx self.plaintext = ptx self.nvl_elms = nvl_elms if len(ctx) > 0: self.n_elms = len(ctx) if len(ptx) > 0: self.n_elms = len(ptx) def update_ctx(self, ctx): self.cyphertext = ctx def update_ptx(self, ptx): self.plaintext = ptx def find_elms(self): #elms in ctx for i in range(len(self.cyphertext)): if self.cyphertext[i] not in self.nvl_elms: self.nvl_elms.append(self.cyphertext[i]) print(self.cyphertext[i]) def frqnc_of_elm(self, elm): e_cnt = 0 for i in range(len(self.cyphertext)): if self.cyphertext[i] == elm: e_cnt+= 1 frq = e_cnt / self.n_elms return frq*100 def show_elm_frqs(self): self.frqnc_dict = {} if len(self.nvl_elms) == 0: self.find_elms() for i in range(len(self.nvl_elms)): elm = str(self.nvl_elms[i]) frqnc_of_elm = self.frqnc_of_elm(self.nvl_elms[i]) iPair = {elm : frqnc_of_elm} self.frqnc_dict.update(iPair) print(elm + ": " + str(frqnc_of_elm)) print(self.frqnc_dict) def frqnc_order(self): elms_cpy = self.nvl_elms.copy() for i in range(len(elms_cpy)): cur_high_frqnc = -1 j = i for j in range(len(elms_cpy)): check_elm = elms_cpy[j] check_frqnc = self.frqnc_dict[check_elm] if check_frqnc >= cur_high_frqnc: cur_high_frqnc = check_frqnc high_frqnc_indx = j #remove an elm from elms_cpy if len(elms_cpy) > 0: elm_2_rmv = elms_cpy[high_frqnc_indx] elms_cpy.remove(elm_2_rmv) #print("removed " + elm_2_rmv) print(str(elm_2_rmv) + ": " + str(cur_high_frqnc)) def test_shift(self, shift=0): self.testtext = '' for i in range(len(self.cyphertext)): ascii = ord(self.cyphertext[i]) new_ascii = ascii + shift if new_ascii > 122: new_ascii -= 26 new_chr = chr(new_ascii) self.testtext = self.testtext + (new_chr) def chk_all_shifts(self): for i in range(26): self.test_shift(i) print("shift " + str(i) + " : " + self.testtext) def fast_mod_exp(base, power, modulus=-1): """ A function to do fast modular exponentiation. ------------------------------------------------ Parameters: base - int : base number power - int : power to raise base todo modulus - int : modulus - in the case of Fermat's Little Theroem, the modulus will be equal to the power - Set to -1 as default - if modulus is set to -1 then modulus is set equal to power Return: answer - int : represents base to the power (mod modulus) """ import math if modulus == -1: modulus = power modular_equivalents = [] #these are the modular equivalents of powers of the base max_pow_2chk = 1 while max_pow_2chk < power : modular_equivalents.append(pow(base, max_pow_2chk) % modulus) max_pow_2chk = max_pow_2chk * 2 #if max_pow_2chk > power : #print("The highest power of " + str(base) + " neccesary to represent " + str(base) + "^" + str(power) + " is " + str(max_pow_2chk/2)) max_pow = max_pow_2chk/2 max_pow_copy = max_pow coef_4_binary_expand = [] #the zero-th coeficcient corresponds to the largest power in the decomposition answer = -1 #default for error detection sum_pows_of_bases = 0 solution = "" while max_pow_copy >= 1 and sum_pows_of_bases != power: index_of_power = int(math.log(max_pow_copy, 2)) #this index of power can also be thought of as how many doublings the current max_pow_copy represents if answer == -1: answer = modular_equivalents[index_of_power] sum_pows_of_bases = max_pow_copy solution = str(base) + "^" + str(int(max_pow_copy)) if power - sum_pows_of_bases - max_pow_copy >= 0: if answer != -1: answer = answer * modular_equivalents[index_of_power] % modulus sum_pows_of_bases += max_pow_copy solution = solution + " * " + str(base) + "^" + str(int(max_pow_copy)) max_pow_copy = max_pow_copy / 2 high_rmndr = modular_equivalents[int(math.log(max_pow, 2))] #print("The remainder of the highest power, smaller than " + str(power) + ", moduluo " + str(power) + ", is " + str(high_rmndr)) problem = str(base) + "^" + str(power) + " (mod " + str(modulus) + ")" answer = str(answer) print("The answer is: " + answer) print(problem + " = " + solution + " (mod "+ str(power) +") = " + answer + " (mod " + str(modulus) + ")") return int(answer)
board = [' ' for x in range(10)] def inputmove(letter, pos): board[pos] = letter def printboard(board): print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') def is_winner(board, letter): return ((board[1] == letter and board[2] == letter and board[3] == letter) or \ (board[4] == letter and board[5] == letter and board[6] == letter) or \ (board[7] == letter and board[8] == letter and board[9] == letter) or \ (board[1] == letter and board[4] == letter and board[7] == letter) or \ (board[2] == letter and board[5] == letter and board[8] == letter) or \ (board[3] == letter and board[6] == letter and board[9] == letter) or \ (board[1] == letter and board[5] == letter and board[9] == letter) or \ (board[3] == letter and board[5] == letter and board[7] == letter)) def player_move(): run = True while run: move = int(input('Entre position to place X (1-9) : ')) if move > 0 and move < 10: if free_space(move): run = False inputmove('X',move) else: print('This position is occupied !') else: print('Please type a number within the range') def comp_move(): place=0 possible_moves=[] for x in range(1,10): if board[x]==' ': possible_moves.append(x) for play in ['O','X']: for i in possible_moves: board2=board[:] board2[i]=play if is_winner(board2,play): place=i return place free_corners=[] for i in possible_moves: if i in [1,3,7,9]: free_corners.append(i) if len(free_corners)>0: place=play_random(free_corners) return place free_edges = [] for i in possible_moves: if i in [2, 4, 6, 8]: free_edges.append(i) if len(free_edges) > 0: place = play_random(free_edges) return place def free_space(pos): if (board[pos] == ' '): return True else: return False def board_full(board): if board.count(' ') > 1: return False else: return True def play_random(list): import random return random.choice(list) print('Welcome to TicTacToe') printboard(board) while (not (board_full(board))): if not (is_winner(board, 'O')): player_move() printboard(board) else: print('O wins the game') break if not (is_winner(board, 'X')): move=comp_move() inputmove('O',move) print('Ai placed O in ',move) printboard(board) else: print('X wins the game') break if board_full(board): print("Match tie") break
import json """ Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. """ class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): # solution 1 ,recursive repr on arguments return '{}(val={!r}, left={!r}, right={!r})'.format(self.__class__.__name__, self.val, self.left, self.right) def serialize_1(self) -> str: # solution 1 ,recursive repr on arguments, result string is exec/eval-ready return repr(self) @classmethod def deserialize_1(cls, string: str = None) -> object: # solution 1, eval string containing the command to re-build the bin tree return eval(string, {"__builtins__": None}, {'Node': cls}) def serialize_2(self, sentiel: str = '#') -> list: # solution 2, do a depth-first tree traversal (left branch first), replace missing arcs/children with sentiel object # outputs as list, wrap into json.dumps() to get a string Tlist = [self.val] if self.left is None: Tlist.append(sentiel) else: Tlist.extend(self.left.serialize_2()) if self.right is None: Tlist.append(sentiel) else: Tlist.extend(self.right.serialize_2()) return Tlist @classmethod def deserialize_2(cls, lst: list = None, sentiel: str = '#') -> object: # solution 2, traverse through list obtained via json.loads() , recursively call class initialization on adjacent elements (children) # if sentiel is encountered, replace arc with None def _shift(index): if lst[index] == sentiel: return None, index+1 val = lst[index] left, index = _shift(index+1) right, index = _shift(index) return cls(val, left, right), index return _shift(0)[0] if __name__ == "__main__": node = Node('root', Node('left', Node('left.left')), Node('right')) tree_dump = json.dumps(node.serialize_2()) tree = Node.deserialize_2(json.loads(tree_dump)) assert Node.deserialize_2(Node.serialize_2( node)).left.left.val == 'left.left' print("all tests passed")
#!/usr/bin/env checkio --domain=py run caesar-cipher-encryptor # https://py.checkio.org/mission/caesar-cipher-encryptor/ # This mission is the part of the set. Another one -Caesar cipher decriptor. # # Your mission is to encrypt a secret message (text only, without special chars like "!", "&", "?" etc.) using Caesar cipher where each letter of input text is replaced by another that stands at a fixed distance. For example ("a b c", 3) == "d e f" # # # # Input:A secret message as a string (lowercase letters only and white spaces) # # Output:The same string, but encrypted # # Precondition: # 0<len(text)<50 # -26<delta<26 # # # END_DESC def to_encrypt(text, delta): import string alphabet = string.ascii_lowercase cipher = [] for i in text.lower(): if i == " ": cipher.append(" ") continue if alphabet.index(i)+delta > 26: cipher.append(alphabet[alphabet.index(i)-(26-delta)]) else: cipher.append(alphabet[alphabet.index(i)+delta]) return "".join(cipher) if __name__ == '__main__': # print("Example:") #print(to_encrypt('abc', 10)) # These "asserts" using only for self-checking and not necessary for auto-testing assert to_encrypt("a b c", 3) == "d e f" assert to_encrypt("a b c", -3) == "x y z" assert to_encrypt("simple text", 16) == "iycfbu junj" assert to_encrypt("important text", 10) == "swzybdkxd dohd" assert to_encrypt("state secret", -13) == "fgngr frperg" print("Coding complete? Click 'Check' to earn cool rewards!")
#!/usr/bin/env python3 from typing import List class Person(object): name: str = "" liked_people: List[str] = [] def __init__(self, name: str=""): self.name = name def likes(self,person:object): self.liked_people.append(person.name) bob = Person("Bob") alice = Person("Alice") bob.likes(alice) print(bob.liked_people)
# quick sort def qsort(lst): """ Pick an element, called a pivot, from the array. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values. """ # list is sorted if there's only 1 element if len(lst) < 2: return lst # set first element as pivot. can also select random pos pivot = lst[0] # store_index is index of next item after pivot store_index = lst.index(pivot)+1 # iterate on items from pivot to the end, if item is less than pivot swap items at store index and at i, incr. store_index for i in range(lst.index(pivot)+1, len(lst)): if lst[i] < pivot: lst[store_index], lst[i] = lst[i], lst[store_index] store_index += 1 # swap items at pivot and store_index-1 positions, pivot is now on its sorted pos lst[lst.index(pivot)], lst[store_index - 1] = lst[store_index-1], lst[lst.index(pivot)] # partition the list in before & after pivot chunks a, b = lst[:lst.index(pivot)], lst[lst.index(pivot)+1:] # recursively run qsort on chunks, concatenate their results and insert pivot in between lst = qsort(a)+[pivot]+qsort(b) return lst if __name__ == '__main__': print([3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]) print(qsort([3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]))
import string literals = string.ascii_letters+string.punctuation+string.whitespace ''' Linear Feedback shift register ''' def stream1(i, a1=1, a2=2): ''' a1,a2 (int) - taps to randomize key value e1,e2 (int) - initial keys (seed) Ei+3=a1*Ei+1+a2*Ei+2 (mod alphabet) ''' e1, e2 = 2, 4 for n in range(i): e3 = (a1*e1+a2*e2) % len(literals) yield e3 e1, e2 = e2, e3 def encrypt1(plaintext): ''' a1,a2 (int) - taps to randomize key value e1,e2 (int) - initial keys (seed) Ei+3=a1*Ei+1+2*Ei+2 (mod alphabet) ''' stream = stream1(len(plaintext)) ciphertext = "" for char in plaintext: ciphertext += literals[(literals.index(char) + next(stream)) % len(literals)] return ciphertext def decryp1(ciphertext): stream = stream1(len(ciphertext)) plaintext = "" for char in ciphertext: plaintext += literals[(literals.index(char) - next(stream)) % len(literals)] return plaintext secret = encrypt1("Meet me at the fucking bar!") print(secret) plain = decryp1(secret) print(plain)
#!/usr/bin/env checkio --domain=py run painting-wall # https://py.checkio.org/mission/painting-wall/ # Nicola has built a simple robot for painting of the wall. The wall is marked at each meter and the robot has a list of painting operations. Each operation describes which part of wall it needs to paint as a range from place to place, inclusively. For example: the operation [1, 5] means to paint the sections from 1 to 5 meters including sections 1 and 5. Operations are executed in the order they are placed in the list of operations. If the range of various operations are overlapped, thenthey must be counted once. # # Stephan has prepared a list of operations, but we need to check it before the robot executes its painting plan. You are given the number of meters on the walls which need painting, (the painted zones can be separated by non painted parts) and the list of operations prepared by Stephan, you should determine the number of operations from this list required to paint the designated length of the wall. If it's impossible to paint that length with the given operations, then return -1. # # # # Input:Two arguments.The required length of the wall that should be painted, as integer.A list of the operations that contains the range (inclusive) as a list of two integers. # # Output:The minimum number of operations. If you cannot paint enough of the length with the given operations, return -1. # # Hint:To handle the beginning-end of the list, you could try running a binary search. # # Precondition: # 0 < len(operations) ≤ 30 # all(0 < x < 2 * 10 ** 18 and 0 < y < 2 * 10 ** 18 for x, y inoperations) # 0 < required < 2 * 10 ** 18 # # # END_DESC def checkio(required, operations): painted = range(operations[0][0], operations[0][1]+1) print("initial compare of painted & operations") if len(painted) >= required: return 1 print("not enough, count+1") count = 1 print("loop start") for i in operations[1:]: if i[0] in painted and i[1] in painted: print("area already painted, don't increase counter and check next area") continue elif i[0] in painted: print( "start of area is in painted zone, extend painted zone to end of this area") painted = range(painted[0], i[1]+1) if len(painted) >= required: count += 1 break else: count += 1 continue elif i[1] in painted: print( "end of area is in painted zone, extend painted zone so it starts at start of this area") painted = range(i[0], painted[len(painted)-1]+1) if len(painted) >= required: count += 1 break else: count += 1 continue else: print("new area") pass else: if len(painted) < required: count = -1 # for loop break goes here return count if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing #assert checkio(5, [[1, 5], [11, 15], [2, 14], [21, 25]]) == 1, "1st" assert checkio(6, [[1, 5], [11, 15], [2, 14], [21, 25]]) == 2, "2nd" #assert checkio(11, [[1, 5], [11, 15], [2, 14], [21, 25]]) == 3, "3rd" #assert checkio(16, [[1, 5], [11, 15], [2, 14], [21, 25]]) == 4, "4th" #assert checkio(21, [[1, 5], [11, 15], [2, 14], [21, 25]]) == -1, "not enough" #assert checkio(1000000011, [[1, 1000000000], [11, 1000000010]]) == -1, "large"
from counting_sort import counting_sort from math import log10 def radix_sort(arr: list, base: int = 10) -> list: # only for non-negative integers max_digits = int(log10(max(arr)))+1 F = [[] for l in range(base)] for p in range(max_digits): for num in arr: digit = (num // base**p) % base F[digit].append(num) arr = [d for l in F for d in l] F = [[] for l in range(base)] return arr if __name__ == "__main__": arr = [345, 2342, 1, 23, 923, 122, 4, 0, 99] assert radix_sort(arr) == sorted(arr) print("all done!")
def solution(arr1: list, arr2: list, target: int) -> tuple: # all-zeros in both arrays if arr1 == arr2 and set(arr1) == {0}: return None # equivalent arrays if arr1 == arr2: pass s = set(arr1) def helper(s: set, arr: list, target: int): for num in arr: if (target - num) in s: return (target-num, num) # check if there is a pair that sums to target # if not, increase/decrease target by 1 for inc in range(0, target): t1 = target+inc a1 = helper(s, arr2, t1) if a1: return a1 t2 = target-inc a2 = helper(s, arr2, t2) if a2: return a2 if __name__ == "__main__": arr1 = [-1, 3, 8, 2, 9, 5] arr2 = [4, 1, 2, 10, 5, 20] target = 24 print(solution(arr1, arr2, target))
""" Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds. """ import time from datetime import datetime, timedelta def foo(*args): print(f"{time.ctime()}: foo was invoked") def scheduler(foo, n): print(f"job {foo} is scheduled after {n}ms at {(datetime.now()+timedelta(microseconds=n*1000)).strftime('%c')}") time.sleep(n/1000) return foo(n) if __name__ == "__main__": n = 5000 scheduler(foo, n)
# Recursively traverse the dictionary [node] to find occurrences of [kv] key and output their values def findkeys(node, kv): if isinstance(node, list): for i in node: for x in findkeys(i, kv): yield x elif isinstance(node, dict): if kv in node: yield node[kv] for j in node.values(): for x in findkeys(j, kv): yield x d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'nested_key1': {'inner_key_1': 'inner_val_1', 'inner_key_2': 'inner_val_2', 'innerkey': 'innerval-d'}, 'nested_key2': [{'l_key_1': 'l_val_1'}, {'innerkey': 'innerval-d-l'}]} for node in d.values(): print(list(findkeys(node, 'innerkey')))
#!/usr/bin/env checkio --domain=py run matrix-pattern # https://py.checkio.org/mission/matrix-pattern/ # To explore new islands and areas Sophia uses automated drones. But she gets tired looking at the monitors all the time. Sophia wants to teach the drones to recognize some basic patterns and mark them for review. # # The drones have a simple optical monochromatic image capturing system. With it an image can be represented as a binary matrix. You should write a program to search a binary matrix (a pattern) within another binary matrix (an image). The recognition process consists of scanning the image matrix row by row (horizontal scanning) and when a pattern is located on the image, the program must mark this pattern. To mark a located pattern change 1 to 3 and 0 to 2. The result will be the image matrix with the located patterns marked. # # The patterns in the image matrix are not crossed, because you should immediately mark the pattern. # # # # Input:Two arguments. A pattern as a list of lists and an image as a list of lists. # # Output:The marked image as a matrix as a list of list. # # Precondition: # 1<image_width ≤ 10 # 1<image_height ≤ 10 # 1<pattern_width ≤ 10 # 1<pattern_height ≤ 10 # |pattern|<|image| # ∀ x ∈ data : x == 0 or x == 1 # # # # END_DESC def checkio(pattern, image): return [] # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio([[1, 0], [1, 1]], [[0, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 1, 0], [1, 1, 0, 1, 1], [0, 1, 1, 0, 0]]) == [[0, 3, 2, 1, 0], [0, 3, 3, 0, 0], [3, 2, 1, 3, 2], [3, 3, 0, 3, 3], [0, 1, 1, 0, 0]] assert checkio([[1, 1], [1, 1]], [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) == [[3, 3, 1], [3, 3, 1], [1, 1, 1]] assert checkio([[0, 1, 0], [1, 1, 1]], [[0, 0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 1, 1, 1, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1, 0], [1, 1, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 0, 0], [0, 1, 1, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) == [[0, 2, 3, 2, 0, 0, 0, 2, 3, 2], [0, 3, 3, 3, 0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 2, 3, 2, 0, 0, 0], [2, 3, 2, 0, 3, 3, 3, 0, 1, 0], [3, 3, 3, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 2, 3, 2, 0], [0, 1, 1, 0, 0, 0, 3, 3, 3, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
def dutch_flag(pivot, myList): #print(type(myList)) #print(type(pivot)) less = [] higher = [] middle = [] pivot = myList[pivot] print("privot is " + str(pivot)) #O(n) time #O(n) space, with n being the length of myList for item in myList: if(item > pivot): higher.append(item) elif(item == pivot): middle.append(item) else: less.append(item) print(less+middle+higher) def main(): myList = [0,1,2,3,2,1,0,3] pivot = 4 dutch_flag(pivot, myList) main()
''' Binary search practice Let's get some practice doing binary search on an array of integers. We'll solve the problem two different ways—both iteratively and resursively. Here is a reminder of how the algorithm works: Find the center of the list (try setting an upper and lower bound to find the center) Check to see if the element at the center is your target. If it is, return the index. If not, is the target greater or less than that element? If greater, move the lower bound to just above the current center If less, move the upper bound to just below the current center Repeat steps 1-6 until you find the target or until the bounds are the same or cross (the upper bound is less than the lower bound). Problem statement: Given a sorted array of integers, and a target value, find the index of the target value in the array. If the target value is not present in the array, return -1. ''' # Iterative solution # First, see if you can code an iterative solution (i.e., one that uses loops). If you get stuck, the solution is below. def binary_search(array, target): min = 0 max = len(array) - 1 while min <= max: mid = (min + max) // 2 if target == array[mid]: return mid elif target > array[mid]: min = mid + 1 else: max = mid - 1 return -1 for r in [4, 3, 7, 6, 100]: array = [r for r in range(r)] print(array) for i in range(r): result = binary_search(array, i) assert result == i, 'r={} i={} result={}'.format(r, i, result) def test_function(test_case): answer = binary_search(test_case[0], test_case[1]) if answer == test_case[2]: print('Pass!') else: print('Fail!') array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 6 index = 6 test_case = [array, target, index] test_function(test_case) ''' TC: log n since: n * (1 / 2)^S = 1 negative exponents to rearrange the fraction n * 2^(-S) = 1 n = 1 / 2^(-S) n = 2^S log2 (n) = S S (time complexity) = log n SC: O(n) '''
from pulp import * # 0 <= x <= 3 x = LpVariable("x", 0, 3) # 0 <= y <= 1 y = LpVariable("y", 0, 1) prob = LpProblem("Just Starting", LpMinimize) # Constraint x + y <= 2 prob += x + y <= 2 # Objective function -4*x + y prob += -4*x + y status = prob.solve() prob.writeLP("simple.lp") prob.solve() if LpStatus[prob.status] == "Optimal": print "Optimal: x = {}, y = {}, objective function: {}".format(value(x), value(y), value(-4*x + y)) else: print LpStatus[prob.status]
def testit(s): print(s) ret =[] if len(s) == 0 : return "" elif len(s) == 1 : return s else: # if len(s) even if len(s) % 2 == 0: for i in range(int(len(s)/2)) : if ord(s[2*i]) == ord(s[2*i+1]): ret.append(s[2*i]) elif ord(s[2*i]) + 1 == ord(s[2*i+1]): ret.append(s[2*i]) else: ret.append(chr(int((ord(s[2*i])+ord(s[2*i+1]))/2))) else : for i in range(int((len(s)-1)/2)) : if ord(s[2*i]) == ord(s[2*i+1]): ret.append(s[2*i]) elif ord(s[2*i]) + 1 == ord(s[2*i+1]): ret.append(s[2*i]) else: ret.append(chr(int((ord(s[2*i])+ord(s[2*i+1]))/2))) ret.append(s[len(s)-1]) return ''.join(ret)
def comp(array1, array2): if array1 == None and array2 == []: return False if array2 == None and array1 ==[]: return False if array1 == [] and array2 != []: return False print(array1, array2) for i in range(len(array1)): if array1[i]**2 not in array2: return False else: array2.remove(array1[i]**2) return True # your code def comp(array1, array2): try: return sorted([i ** 2 for i in array1]) == sorted(array2) except: return False
def format_duration(seconds): #super basic approach No use of time functions if seconds == 0: return 'now' min = 60 hour = 60 * min day = 24 * hour year = 365 * day ret = [] y = seconds // year d = (seconds - y * year) // day h = (seconds - y * year - d * day) // hour m = (seconds - y * year - d * day - h * hour) // min s = (seconds - y * year - d * day - h * hour - m * min) print(str(y)+' years '+str(d)+ ' days '+ str(h) + ' hours '+ str(m) + 'minutes' +str (s)+'seconds') if s != 0 : #and y+d+h+m == 0: if s == 1: ret.append('1 second') else: ret.append(str(s)+' seconds') if m != 0 : if m == 1: ret.insert(0,'1 minute') else: ret.insert(0,str(m)+' minutes') if h != 0 : if h == 1: ret.insert(0,'1 hour') else: ret.insert(0,str(h)+' hours') if d != 0 : if d == 1: ret.insert(0,'1 day') else: ret.insert(0,str(d)+' days') if y != 0 : if y == 1: ret.insert(0,'1 year') else: ret.insert(0,str(y)+' years') if len(ret) == 1: return ret[0] elif len(ret) == 2: return ret[0]+' and '+ret[1] elif len(ret) == 3: return ret[0]+', '+ret[1]+' and '+ret[2] elif len(ret) == 4: return ret[0]+', '+ret[1]+', '+ret[2]+' and '+ret[3] else: return ret[0]+', '+ret[1]+', '+ret[2]+', '+ret[3]+' and '+ret[4]
#level 6 print nicely integer with 10 powers def simplify(n): if n == 0: return '' ret = '' p = 0 while True: if n == 0: # n = 0 ou fin du traitement if ret[-1]=='+': ret = ret[0:-1] return ret break if p == 0: # first digit if n % 10 != 0: ret += str(n%10) n = ( n - n % 10 ) / 10 p += 1 if n % 10 == 0: # multiple of 10 n = n / 10 p += 1 else: ret = str( int(n% 10))+'*'+str(10**p)+'+'+ ret n = ( n - n % 10 ) / 10 # si fini on le triate avec le premier test p += 1 # return ret print(simplify(5643)) # result is 5*1000+6*100+4*10+3 NICE """ Given a positive integer as input, return the output as a string in the following format: Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number. Examples Input Output 0 "" 56 "5*10+6" 60 "6*10" 999 "9*100+9*10+9" 10004 "1*10000+4" Note: input >= 0 """
def am_I_afraid(day,num): if day == "Monday" and num == 12: return True elif day == "Tuesday" and num > 95: return True elif day == "Wednesday" and num == 34: return True elif day == "Thursday" and num == 0: return True elif day == "Friday" and num %2 == 0: return True elif day == "Saturday" and num == 56 : return True elif day == "Sunday" and (num == 666 or num == -666): return True else: return False #selective number def am_I_afraid(day,num): return { 'Monday': num == 12, 'Tuesday': num > 95, 'Wednesday': num == 34, 'Thursday': num == 0, 'Friday': num % 2 == 0, 'Saturday': num == 56, 'Sunday': num == 666 or num == -666, }[day]
def mygcd(x, y): if x < y: x,y = y, x if y == 0: return x return mygcd(y, x%y) """ One way to find the GCD of two numbers is Euclid’s algorithm, which is based on the observation that if r is the remainder when a is divided by b, then gcd(a, b)= gcd(b, r). As a base case, we can use gcd(a, 0) = a."""
def points(games): ret = 0 for i in range(len(games)): if games[i][0]>games[i][2]: ret += 3 elif games[i][0] == games[i][2]: ret += 1 return ret
# This program says hello and asks for my name print('Hello world') print('What is your name?') #ask for their name myName = input() print('It is good to meet you, ' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') #ask for their age myAge = input() print('You will be ' + str(int(myAge) +1) + ' in a year.') myAge = int(myAge) password = 'swordfish' if myName == 'Mary': print('Hello Mary') if password == 'swordfish': print('Access granted.') else: print('Wrong password.') elif myAge < 12: print(myAge) elif myAge > 2000: print('old') name = '' while name != 'your name': print('Please type your name') name=input() print('Thank you')
test = ' lskjhsjlkh ' import re #import Regex tools def myStrip(input, subText=''): #if subText='' strip() else remove subText if subText == '': exspaceRegex = re.compile(r'(\s+)*(.*)(\s+)*') return exspaceRegex.search(input).group(2) else: subRegex = re.compile(subText) return subRegex.sub('', input) print(myStrip('sklghlkfh kljlkfzj ', 'l')) print(myStrip('sklghlkfh kljlkfzj ', 'kl')) print(myStrip(' sklghlkfh kljlkfzj '))
# iis the input uppercase def is_uppercase(inp): if inp == inp.upper(): return True else: return False print(is_uppercase('HELLO'))
def sum_even_numbers(seq): ret = 0 if seq == []: return 0 else: for i in range(len(seq)): if int(seq[i]) == seq[i] and seq[i] % 2 == 0: ret += seq[i] return ret pass """ return the sum of even number. 4 or 4.000 included. """
def is_orthogonal(u, v): ret = 0 for i in range(len(u)): ret += u[i]*v[i] return ret == 0 pass def is_orthogonal(u, v): return sum(i*j for i,j in zip(u,v)) == 0 is_orthogonal = lambda u, v: not sum(a * b for a, b in zip(u, v))
# @TIME : 2019/4/2 上午8:36 # @File : 有效的括号.py import time class Solution1: def isValid(self, s): stack = [] dict1 = {"(": ")", "{": "}", "[": "]"} for elem in s: if elem in dict1.keys(): stack.append(elem) elif elem in dict1.values(): if stack == [] or dict1[stack.pop()] != elem: return False else: return False return stack == [] class Solution2: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == '' # -------------------- class Empty(Exception): pass class ArrayStack: def __init__(self): self._data = [] def len(self): return len(self._data) def is_empty(self): return len(self._data) == 0 def push(self, item): return self._data.append(item) def top(self): if self.is_empty(): raise Empty("Stack is empty") return self._data[-1] def pop(self): if self.is_empty(): raise Empty("Stack is empty") return self._data.pop() class Solution3: def isValid(self, s): lefty = "({[" righty = ")}]" S = ArrayStack() for c in s: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False if righty.index(c) != lefty.index(S.pop()): return False return S.is_empty() input_1 = "()[{}]" input_2 = "{[]]}" start1 = time.time() aa = Solution1() end1 = time.time() time1 = end1 - start1 # print(aa.isValid(input_1)) print('第一个程序运行时间:', str(time1)) time.sleep(1) start2 = time.time() bb = Solution2() end2 = time.time() time2 = end2 - start2 # print(bb.isValid(input_1)) print('第二个程序运行时间:', str(time2)) time.sleep(1) start3 = time.time() bb3 = Solution3() end3 = time.time() time3 = end3 - start3 # print(bb.isValid(input_1)) print('第三个程序运行时间:', str(time3)) print("三个程序,最短时间 = ", min(time1, time2, time3))
# @TIME : 2019/10/9 下午01:04 # @File : 数组中第K大元素_215.py """ 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明: 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 """ import heapq import time b = [3,2,1,5,6,4] class Solution: def findKthLargest(self, nums, k): heap = nums # print(heap) self.heapsort(heap) # print(heap) # new = [] # for i in heap: # if i not in new: # new.append(i) new = heap[::-1] print(new) find = new[k-1] return find def max_heapify(self, heap, heapsize, root): """堆调整""" left = 2*root + 1 right = left + 1 larger = root if left < heapsize and heap[larger] < heap[left]: larger = left if right < heapsize and heap[larger] < heap[right]: larger = right if larger != root: heap[larger], heap[root] = heap[root], heap[larger] self.max_heapify(heap, heapsize, larger) def build_max_heap(self, heap): """构造一个堆, 未进行排序""" heapsize = len(heap) for i in range((heapsize-2)//2, -1, -1): # 从后往前调整 self.max_heapify(heap, heapsize, i) def heapsort(self, heap): """将根节点取出与最后一位做对调,对前面len-1个节点继续进行对调整过程""" self.build_max_heap(heap) for i in range(len(heap) - 1, -1, -1): heap[0], heap[i] = heap[i], heap[0] self.max_heapify(heap, i, 0) # size 不断减小,这里是i class Solution2: def findKthLargest(self, nums, k): return heapq.nlargest(k, nums)[-1] if __name__ == "__main__": # nums = [3,2,1,5,6,4] # k = 2 nums = [3,2,3,1,2,4,5,5,6] k = 4 t1 = time.time() S = Solution() find = S.findKthLargest(nums, k) t2 = time.time() print(find) print("time1:",t2-t1) t3 = time.time() S2 = Solution2() find2 = S2.findKthLargest(nums, k) t4 = time.time() print(find2) print("time2:",t4-t3)
# @TIME : 2019/6/9 上午1:19 # @File : Maximum Length of Repeated Subarray_718.py import numpy as np # Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. # Input: # A: [1,2,3,2,1] # B: [3,2,1,4,7] # Output: 3 # Explanation: # The repeated subarray with maximum length is [3, 2, 1]. # Note # 1 <= len(A), len(B) <= 1000 # 0 <= A[i], B[i] < 100 A = [1, 2, 3, 2, 1] B = [3, 2, 1, 4, 90, 1, 2, 3, 2, 1] def find(A, B): dp = [[0 for _ in range(len(A)+1)] for _ in range(len(B)+1)] for i in range(1, len(B)+1): for j in range(1, len(A)+1): if B[i-1] == A[j-1]: dp[i][j] = dp[i-1][j-1] + 1 return max(max(row) for row in dp) print(find(A, B)) # class Solution: # def __init__(self, A, B): # self.A = A # self.B = B # # def findLength(self): # print('A = ', A) # print('B = ', B) # # dp = [[0 for _ in range(len(self.B) + 1)] for _ in range(len(self.A) + 1)] # print(np.array(dp)) # # 从第一格开始 # for i in range(1, len(self.A) + 1): # print('i = ', i) # for j in range(1, len(self.B) + 1): # print('j = ', j) # print("value A[{}] {}, B[{}] {}".format(i-1, self.A[i-1], j-1, self.B[j-1]) ) # if self.A[i-1] == self.B[j-1]: # dp[i][j] = dp[i-1][j-1] + 1 # print('\n') # print(np.array(dp)) # else: # dp[i][j] = 0 # # rel = max(max(row) for row in dp) # print('rel =', rel) # return rel # # a = Solution(A, B) # a.findLength()
#Autor: Yasmín Landaverde Nava #Descripción: este programa calcula el cosoto toal de los boletos para un concierto. def calcularPago(boletosA, boletosB, boletosC): costoA = boletosA * 3250 costoB = boletosB * 1730 costoC = boletosC * 850 totalPago = costoA + costoB + costoC return totalPago def imprimirPago(boletosA, boletosB, boletosC): totalPago = calcularPago(boletosA, boletosB, boletosC) print("El costo total es: $", totalPago ) def main(): boletosA = int(input("¿Cuántos bolestos en sección A quieres?: ")) boletosB = int(input("¿Cuántos bolestos en sección B quieres?: ")) boletosC = int(input("¿Cuántos bolestos en sección C quieres?: ")) calcularPago(boletosA, boletosB, boletosC) imprimirPago(boletosA, boletosB, boletosC) main()
def substractNumber(num1,num2): res = num1-num2 return res vals = substractNumber(20,10) print(vals)
num = 123 rev=0 while(num>0): rem=num%10 rev=(rev*10)+rem num=num//10 print("reverse:",rev)
num=int(input("enter a limit")) lst=[] even=[] odd=[] for i in range(1,(num+1)): lst.append(i) for n in lst: if(n%2==0): even.append(n) else: odd.append(n) print(lst) print(odd) print(even)
from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cache = set() for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == ".": continue row = str(i)+"row"+board[i][j] col = str(j)+"col"+board[i][j] box = str(i//3)+str(j//3)+"col"+board[i][j] if row in cache or col in cache or box in cache: return False cache.add(row) cache.add(col) cache.add(box) return True solution = Solution() board = [ ["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"] ] print(solution.isValidSudoku(board))
# Definition for singly-linked list. class ListNode: def __init__(self, x, next=None): self.val = x self.next = next def overlapping_lists(l1: ListNode, l2: ListNode) -> ListNode: root1, root2 = detectCycle(l1), detectCycle(l2) if not root1 and not root2: return overlapping_lists_without_cycles(l1, l2) elif (root1 and not root2) or (root2 and not root1): return None else: tmp = root2 while tmp: tmp = tmp.next if tmp is root1 or tmp is root2: break return root2 if tmp is root1 else None # TODO: write this func 7.4 def overlapping_lists_without_cycles(l1: ListNode, l2: ListNode) -> ListNode: return l1 def detectCycle(head: ListNode) -> ListNode: fast = slow = head while fast and fast.next and fast.next.next: slow = slow.next fast = fast.next.next if slow == fast: slow = head while slow != fast: slow = slow.next fast = fast.next return slow return None cycle = ListNode(10, ListNode(11, ListNode(12))) cycle.next = cycle l1 = ListNode(0, ListNode(1, ListNode(2, cycle))) l2 = ListNode(5, ListNode(6, cycle)) print(overlapping_lists(l1, l2))
# Definition for singly-linked list. class ListNode: def __init__(self, x, next=None): self.val = x self.next = next def list_pivoting(l: ListNode, x: int) -> ListNode: less_head = less = ListNode(0) equal_head = equal = ListNode(0) greater_head = greater = ListNode(0) while l.next: if l.val < x: less.next = l less = less.next elif l.val > x: greater.next = l greater = greater.next else: equal.next = l equal = equal.next l = l.next less.next = equal_head.next equal.next = greater_head.next return less_head.next l = ListNode(3, ListNode(2, ListNode(2, ListNode(11, ListNode(7, ListNode(5, ListNode(11))))))) print(list_pivoting(l, 7))
# Definition for singly-linked list. class ListNode: def __init__(self, x, next=None): self.val = x self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: result = ListNode(0, head) left = result for i in range(m-1): left = left.next middle, right = left.next, left.next.next for i in range(n-m): middle.next = right.next right.next = left.next left.next = right right = middle.next return result.next solution = Solution() head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) print(solution.reverseBetween(head, 2, 4))
from bs4 import BeautifulSoup import requests import pyttsx3 def get_info(country='india'): url = 'https://www.worldometers.info/coronavirus/country/{}/'.format(country) try: response = requests.get(url) #print(response) soup = BeautifulSoup(response.text,'html.parser') data = soup.findAll('div',{'class':'maincounter-number'}) print("Current Covid-19 India Report") new_data = [] for tc in range(0,len(data)): new_data.append(data[tc].text) print(f"Total Cases: {new_data[0]}".rstrip()) print(f"Total Deaths: {new_data[1]}".rstrip()) print(f"Total Recovered: {new_data[2]}".rstrip()) engine = pyttsx3.init() engine.setProperty('rate',200) engine.say(f'Total Cases in {country} is {new_data[0]} and Total Deaths are {new_data[1]}') engine.say(f'Total Recovered Cases are {new_data[2]}') engine.runAndWait() except : print("No Internet Connection") while(1): print("1.Get Covid-19 Report\n2.Exit") ch = input("Choose Your Choice:") if ch == "1": country = input('Enter the Country!') get_info(country) elif ch == "2": exit() else: print("Invalid Choice")
def unija(dict1,dict2): """ radi uniju nad 2 recnika""" dictVracanje={} #dict koji se vraca for (key1, value1) in dict1.items(): dictVracanje[key1]=value1 #ovde dodajem sve iz dict1 u dictVracanje for (key2, value2) in dict2.items(): if key2 not in dict1.keys(): #proverava da li je kljuc iz drugog dict-a u prvom dict-u dictVracanje[key2] = value2 #ovde dodajem samo one koji nisu vec u dict1 samim tim i u dictVracanje else: dictVracanje[key2] += value2 #ako se key2 vec nalazi u dictVracanje onda mu samo uvecaj vrednost za value2 return dictVracanje #vracam dictVracanje def presek(dict1,dict2): """ radi presek nad 2 recnika""" dictVracanje = {} #dict koji se vraca for (key1, value1) in dict1.items(): if key1 in dict2.keys(): #provera da li je kljuc iz prvog dict-a i u drugom dict-u #ovde dodajem samo one koji su i u dict2 i u dict1 pom = dict2[key1] #pomocna promenjiva koja cuva vrednost za kljuc key1 iz dict2 dictVracanje[key1] = value1 #ovde dodajem key1 i njegovu vrednost(iz dict1) u dictVracanje dictVracanje[key1] += pom #ovde uvecavam vrednost kljuca key1 u dictVracanje za pomocnu promenjivu(vrednost iz dict2) return dictVracanje #vracam dictVracanje def komplement(dict1,dict2): """ radi komplement 2 recnika""" dictVracanje = {} #dict koji se vraca for (key1, value1) in dict1.items(): if key1 not in dict2.keys(): #ovde dodajem samo one koji su u direktorijumu1 a ne u direktorijumu2 dictVracanje[key1] = value1 #dodajem key1 i njegovu vrednost ako je prosao kriterijum return dictVracanje #vracam dictVracanje
import multiprocessing import time def square(n, result): for i in n: time.sleep(0.5) print(multiprocessing.current_process().name) result.put(i*i) def cube(n, result): for i in n: time.sleep(0.5) print(multiprocessing.current_process().name) result.put(i*i*i) if __name__ == '__main__': a = [2, 3, 4] q_s = multiprocessing.Queue() q_c = multiprocessing.Queue() p1 = multiprocessing.Process(name='Square', target=square, args=(a, q_s)) p2 = multiprocessing.Process(name='Cube', target=cube, args=(a, q_c)) p1.start() p2.start() p1.join() p2.join() while q_s.empty() is False: print(q_s.get()) while q_c.empty() is False: print(q_c.get())
''' A surface filled with one hundred medium to small sized circles. Each circle has a different size and direction, but moves at the same slow rate. Display the instantaneous intersections of the circles Implemented by William Ngan <http://metaphorical.net> 4 April 2004 Processing v.68 <http://processing.org> Port to Processing.py/Processing 2.0 by Ben Alkov 29 August - 5 September 2014 ''' from circle import Circle circles = [] def setup(): global circles size(600, 600) frameRate(30) noFill() ellipseMode(CENTER) circles = [Circle(random(width), random(height), 15 + random(20), i) for i in range(50)] # 50 circles def draw(): background(255) noStroke() fill(0) for circle in circles: circle.render(circles) noFill() stroke(255) for circle in circles: circle.renderHair()
# -*- coding: utf-8 -*- __author__ = 'wangwenjie' __data__ = '2018/5/28 上午9:24' __product__ = 'PyCharm' __filename__ = 'decorator_pattern' # 装饰器模式 decorator pattern class LogManager(): @staticmethod def log(func): def wrapper(*args): print('Visit func %s', func.__name__) return func(*args) return wrapper class Beverage(): name = '' price = 0.0 type = 'BEVERAGE' @LogManager.log def getPrice(self): return self.price def setPrice(self, price): self.price = price def getName(self): return self.name class coke(Beverage): def __init__(self): self.name = 'coke' self.price = 4.0 class milk(Beverage): def __init__(self): self.name = 'milk' self.price = 5.0 class drinkDecorator(): def getName(self): pass def getPrice(self): pass class iceDecorator(drinkDecorator): def __init__(self, beverage): self.beverage = beverage def getName(self): return self.beverage.getName() + '+ice' def getPrice(self): return self.beverage.getPrice() + 0.3 class sugerDecorator(drinkDecorator): def __init__(self, beverage): self.beverage = beverage def getName(self): return self.beverage.getName() + '+suger' def getPrice(self): return self.beverage.getPrice() + 0.5 if __name__ == '__main__': coke_cola = coke() print('Name: %s' % coke_cola.getName()) print('Price: %s' % coke_cola.getPrice()) ice_coke = iceDecorator(coke_cola) print('Name: %s' % ice_coke.getName()) print('Price: %s' % ice_coke.getPrice()) ''' 定义: 动态的给对象添加一些额外的职责 和Proxy Pattern 的区别: 装饰器模式是代理模式的一种特殊情况,decorator_pattern侧重对主题类功能的加强或减弱; proxy_pattern侧重对主题类过程的控制 AOP Aspect Oriented Programming 面向切面编程 如果几个或者更多个逻辑过程中,有重复的操作行为, 就可以将这些行为提取出来(即形成切面), 进行统一管理和维护 OOP Object Oriented Programming 面向对象编程 ''' ''' 三、装饰器模式的优点和应用场景 优点: 1、装饰器模式是继承方式的一个替代方案,可以轻量级的扩展被装饰对象的功能; 2、Python的装饰器模式是实现AOP的一种方式,便于相同操作位于不同调用位置的统一管理。 应用场景: 1、需要扩展、增强或者减弱一个类的功能,如本例。 四、装饰器模式的缺点 1、多层装饰器的调试和维护有比较大的困难。 '''
# Aapo Tommila - 0553657 # Let's make a game of guess a number game # At this game computer generates a number # and a user should guess it! ######################################### # Ingredients: # #---------------------------------------# # from random import randint # # print() # # input() # # if-elif-else # # int() # ######################################### # Import random module from random import randint if __name__ == "__main__": # Print welcomming words print('Let\'s play guess a number game') # Get a number from user by input() function guess_int = input('Enter a guess between 0 - 10: ') # Convert the user's number to integer (as long as input() returns string) guess = int(guess_int) # Generate random number using randint randomi = randint(0,10) # Check if user's guess equal to computer's number if guess == randomi: # Print to user that the guess is right print ('Right!') print (randomi) # Check if user's guess is morte than computer's number elif guess > randomi: # Print to user that it is more print ('Too high! The number was',randomi,'! :p') # If it's not equal or more else: print ('Too low! The number was',randomi,'! :p') # Print that it's too small
# Let's make a game of guess a number game # At this game computer generates a number # and a user should guess it! ######################################### # Ingredients: # #---------------------------------------# # from random import randint # # print() # # input() # # if-elif-else # # int() # ######################################### # Import random module from random import randint if __name__ == "__main__": # Print welcomming words print('Hello!') # Get a number from user by input() function user_number = input('your randing from 0 to 10,') # Convert the user's number to integer (as long as input() returns string) user_number_int = int(user_number) # Generate random number using randint random_num = randint(0,10) # Check if user's guess equal to computer's number if user_number_int == random_num: # Print to user that the guess is right print('Concrats! Correct number!') # Check if user's guess is morte than computer's number elif user_number_int > random_num: # Print to user that it is more print('Number is too big!') # If it's not equal or more else: # Print that it's too small print('Number is too small')
import os # List of Fibonacci numbers fibonacci_sequence = [0,1,1,2,3,5,8,13,21,34,55] # We can make a fibonacci sequence by ourselves our_fibonacci_sequence = [] amount_numbers = 15 first_number = 0 second_number = 1 for number in range(amount_numbers): print(first_number) our_fibonacci_sequence.append(first_number) new_fibconacci_number = first_number + second_number first_number = second_number second_number = new_fibconacci_number # Open files in the folder #path = '/some/path/to/file' path = 'C:/Data/TextFiles' try: for filename in os.listdir(path): file_path = '{}/{}'.format(path,filename) text_file = open(file_path, 'r') line = text_file.readline() print(line) except: print('No such directory! Check if you wrote it correctly!')
import matplotlib.pylab as plt LETTERS=' ABCDEFGHIJKLMNOPQRSTUVWXYZ' def frequency_analysis(plain_text): plain_text=plain_text.upper() #using dictionary pair letter_frequency = {} for letter in LETTERS: letter_frequency[letter]=0 for letter in plain_text: if letter in LETTERS: letter_frequency[letter]+=1 return letter_frequency def plot_distr(letter_frequency): centers = range(len(LETTERS)) plt.bar(centers,letter_frequency.values(), align='center',tick_label=letter_frequency.keys()) plt.xlim([0,len(LETTERS)-1]) plt.show() if __name__ == "__main__": plain_text = "Shannon defined the quantity of information produced by a source, for example the quantity" frequencies = frequency_analysis(plain_text) plot_distr(frequencies)
#!/usr/bin/env python3.5 import sys import re def debug(*args): print("-----------") for arg in args: sys.stdout.write(str(arg) + "\n") print("- - - - - -") print("-----------") class Arguments: """ Class for storing program arguments. Class has these methods: __init__(self, arguments) __str__(self) Class has these public atributes: help Tells if --help is in arguments input Stores name of input file output Stores name of output file finish Tells if --find-non-finishing is in arguments minimize Tells if --minimize is in arguments insensitive Tells if --case-insensitive is in arguments """ help = False # Tells if --help is in arguments input = sys.stdin # Stores name of input file output = sys.stdout # Stores name of output file finish = False # Tells if --find-non-finishing is in arguments minimize = False # Tells if --minimize is in arguments insensitive = False # Tells if --case-insensitive is in arguments __input_set = False # Tells if --input= was set __output_set = False # Tells if --output= was set def __init__(self, arguments): """ Constructor of Class Arguments. There is given only one argument, which is list of strings, where are stored program arguments for parsing. """ for arg in arguments: if arg == "--help" and self.help is False: self.help = True elif (arg == "-f" or arg == "--find-non-finishing") and self.finish is False: self.finish = True elif (arg == "-m" or arg == "--minimize") and self.minimize is False: self.minimize = True elif (arg == "-i" or arg == "--case-insensitive") and self.insensitive is False: self.insensitive = True elif arg.startswith("--input=") and self.__input_set is False: self.input = arg[8:] self.__input_set = True elif arg.startswith("--output=") and self.__output_set is False: self.output = arg[9:] self.__output_set = True else: err("Invalid use of arguments.", 1) exit(1) self.__valide_arguments(len(arguments)) def __str__(self): """ Returns both private and public variable names with their values as string """ return ('help: %s \n' 'input: %s \n' 'output: %s \n' 'finish: %s \n' 'minimize: %s \n' 'insensitive: %s \n' '__input_set: %s \n' '__output_set: %s' )%(str(self.help), str(self.input), str(self.output), str(self.finish), str(self.minimize), str(self.insensitive), str(self.__input_set), str(self.__output_set)) def __valide_arguments(self, num_of_arguments): """ Checks if arguments are valide. Needs number of arguments as parametr. """ if num_of_arguments > 1 and self.help: err("You can't just ask for help and insert another argument(s)...", 1) exit(1) if self.minimize and self.finish: err("You can't just use --minimize and --find-non-finishing argument at once...", 1) exit(1) def print_help(): """ Prints program arguments on stdout. """ sys.stdout.write( 'Usage: python3.6 ./mka.py [--input=filename --output=filename --help -m -f -i]\n\n' '--input=filename Specifies input file. Default value is stdin.\n' '--output=filename Specifies output file. Default value is stdout.\n' '--help Print this message on stdout.\n' '-m, --minimize Minimize state machine.\n' '-f, --find-non-finishing Finds non finishing state of state machine.\n' '-i, --case-insensitive Program will be case insensitive.\n' ) class FiniteStateMachine: """ Class that represents finite state machine. Class can only accept well specified finite state machine. Class has these methods: __init__(self, declaration) __str__(self) minimize(self) rules_to_string(rules) alphabet_to_string(alphabet) states_to_string(states) Class has these atributes: states Set of all states alphabet Set of alphabet rules Set of rules start Starting state fin_states Set of finite states reachable_states Set of reachable states unreachable_states Set of unreachable states finishing_states Set of finishing states non_finishing_states Set of non finishing states nondeterministic_rules List of non deterministic rules epsilon_rules List of rules with epsilon symbol """ states = set() # Set of all states alphabet = set() # Set of alphabet rules = list() # Set of rules start = str() # Starting state fin_states = set() # Set of finite states reachable_states = set() # Set of reachable states unreachable_states = set() # Set of unreachable states finishing_states = set() # Set of finishing states non_finishing_states = set() # Set of non finishing states nondeterministic_rules = list() # List of non deterministic rules epsilon_rules = list() # List of rules with epsilon symbol def __init__(self, declaration): """ Creates new state machine and set all parametrs, also checks if dictionary declaration represents well specified finite state machine. """ # Sets basic atributes self.count = 0 self.states = declaration["states"] self.alphabet = declaration["alphabet"] self.rules = declaration["rules"] self.start = declaration["start_state"] self.fin_states = declaration["fin_states"] self.finishing_states = self.fin_states.copy() # Sets rest of atributes self.__set_reachable(self.start) self.unreachable_states = self.states.difference(self.reachable_states) if self.unreachable_states: tmp = FiniteStateMachine.states_to_string(self.unreachable_states) err("State(s) %s are not reachable."%(tmp), 62) self.__set_non_finishing() if len(self.non_finishing_states) > 1: tmp = FiniteStateMachine.states_to_string(self.non_finishing_states) err("States %s are non finishing."%(tmp), 62) self.__find_nondeterminism() if self.nondeterministic_rules: tmp = FiniteStateMachine.rules_to_string(self.nondeterministic_rules) err("Rules:\n%s\nare non deterministic."%(tmp), 62) self.__set_epsilon() if self.epsilon_rules: tmp = FiniteStateMachine.rules_to_string(self.epsilon_rules) err("Rules:\n%s\nare epsilon rules."%(tmp), 62) def __str__(self): """ Creates and return string representing state machine. """ out = "(\n" out += FiniteStateMachine.states_to_string(self.states) + ",\n" out += FiniteStateMachine.alphabet_to_string(self.alphabet) + ",\n" out += FiniteStateMachine.rules_to_string(self.rules) + ",\n" out += self.start + ",\n" out += FiniteStateMachine.states_to_string(self.fin_states) + "\n)\n" return out def __set_reachable(self, start_state): """ Detects reachable states and sets atribute. """ self.reachable_states.add(start_state) for rule in self.rules: if not (rule["next"] in self.reachable_states) and rule["start"] == start_state: self.__set_reachable(rule["next"]) def __set_non_finishing(self): """ Detects non finishing states and sets both finishing_states and non_finishing_states attributes. """ tmp = True while tmp: tmp = False for rule in self.rules: if rule["next"] in self.finishing_states and not(rule["start"] in self.finishing_states): self.finishing_states.add(rule["start"]) tmp = True self.non_finishing_states = self.states.difference(self.finishing_states) def __find_nondeterminism(self): """ Detects non deterministic rules and sets attribute. """ for rule in self.rules: for cmp in self.rules: if cmp["start"] == rule["start"] and cmp["symbol"] == rule["symbol"]: if cmp != rule: self.nondeterministic_rules.append(rule) def __set_epsilon(self): """ Detects all rules with epsilon symbol. """ for rule in self.rules: if rule["symbol"] == "epsilon": self.epsilon_rules.append(rule) def minimize(self): """ Minimizes finite state machine. """ def split(X, d): """ Splits set of states X into 2 states and return them as list. """ X1 = set() # First set of states X2 = set() # Second set of states next_states = set() # Set of following states of X1 next_of_current = set() # Set of following states of X2 # Spliting X for state in X: if not X1: # First element X1.add(state) # Adds element into set # Initialize next_states set next_states = {r["next"] for r in self.rules if r["start"] == state and r["symbol"] == d} else: # Sets new value for next_of_current next_of_current = {r["next"] for r in self.rules if r["start"] == state and r["symbol"] == d} if next_of_current <= next_states: # Tests if next_of_current is subset of next_states X1.add(state) else: X2.add(state) return [X1, X2] def parse_new_rule(states, symbol, next): """ Creates new rule of state machine. """ new_state = str() new_next = str() isStart = False isFin = False # Join set of states into one state and adds info if state is # starting state of finite state. for state in sorted(list(states)): new_state += state + "_" if state == self.start: isStart = True if state in self.fin_states: isFin = True # Join set of states into one state for state in sorted(list(next)): new_next += state + "_" new_state = new_state[:-1] new_next = new_next[:-1] return {"start":new_state, "symbol":symbol,"next":new_next, "start_state":isStart, "fin_state":isFin} # Algorithm from IFJ Qm = list() # List of sets. Each set of states can be joined into one state # Initializing List of sets. if (self.fin_states): # Adding set of finite states if its not empty set Qm.append(self.fin_states) if (self.states.difference(self.fin_states)): # Adding rest if its not empty set Qm.append(self.states.difference(self.fin_states)) condition = True # Tells if there is possible spliting of future set X next_states = set() # Set of following states new_rules = list() # List of new rules while condition: condition = False # We are optimistic, no spliting will happen new_rules = list() # Deleting all new rules for X in Qm: # Parsing Qm for d in self.alphabet: # Parsing X # New set of following states of states in set X next_states = {r["next"] for r in self.rules if d == r["symbol"] and r["start"] in X } found = False # Tells if we found superset of next_states for Qi in Qm: if next_states.issubset(Qi): found = True # We found, no split will happen new_rules.append(parse_new_rule(X, d, Qi)) # Creates new rule if not found: # We did not found condition = True # Loop must start again X12 = split(X, d) # Splits X into X1 and X2 del Qm[Qm.index(X)] # Removes X from Qm Qm.append(X12[0]) # Adds X1 into Qm Qm.append(X12[1]) # Adds X2 into Qm break # There is no need of continuing if not found: break # There is no need of continuing # Change states, rules, start and fin_state attributes of finite state machine # so machone is now minimized. self.states = {r["start"] : r["next"] for r in new_rules} self.rules = [{"start":r["start"],"symbol":r["symbol"],"next":r["next"]} for r in new_rules] self.start = [r["start"] for r in new_rules if r["start_state"] is True][0] self.fin_states = {r["start"] for r in new_rules if r["fin_state"] is True} def rules_to_string(rules): """ Converts given rules into string. """ output = "{" for rule in rules: if rule["symbol"] == "epsilon": rule["symbol"] = "" rules.sort(key = lambda r:(r["start"], r["symbol"])) for rule in rules: output += "\n" + rule["start"] + " '" + rule["symbol"] + "'" + " -> " output += rule["next"] + "," output = output[:-1] + "\n}" return output def states_to_string(states): """ Converts given states into string. """ out = "{" for state in sorted(list(states)): out += state + ", " out = out[:-2] + "}" return out def alphabet_to_string(alphabet): """ Converts given alphabet into string. """ out = "{" for d in sorted(alphabet): out += "'" + d + "'" + ", " out = out[:-2] + "}" return out def err(message, code): """ Prints error message on stderr and exit program with specific errorcode """ sys.stderr.write(message + "\n") exit(code) def parse_input(args): """ Tries to open input file and parse it. Returns dictionary with keys 'states', 'alphabet', 'rules', 'start_state' and 'finish state', where 'rules' is list of dictionaries with keys 'start', 'symbol' and 'next'. All 3 are strings. 'start_state' is string and rest are sets. """ try: input = args.input if (not (input is sys.stdin)): input = open(args.input, "r") data = input.read() input.close() except: err("Unable to open input file '" + str(args.input) + "' for reading", 2) data = prepare_data(data) # Deletes coments and white characters if args.insensitive: # Check for argument --case-insensitive data = data.lower() # Convert whole input into lowercase data = retrieve_data(data) # Parse input return data def prepare_data(data): """ Deletes all comments and all useless white characters. """ comment = False # Tells if we are in comment apostrophe = False # Tells if we are between 2 apostrophes raw_string = str() # Variable for storing parsed data # Simple state machine where c represents string of length 1 for c in data: if comment: # If we are in comment, we ignore all characters if c == "\n": # expect end of line. comment = False continue elif not apostrophe and c == "#": # Detecting comments comment = True continue elif c == "'": # Detecting apostrophes if not apostrophe: apostrophe = True else: apostrophe = False if(not c.isspace() or (c.isspace() and apostrophe)): # Ignoring white characters raw_string += c return raw_string def retrieve_data(data): """ Parses definition of state machine. Definition should be without spaces and useless white characters. Returns dictionary with keys 'states', 'alphabet', 'rules', 'start_state' and 'finish state', where 'rules' is list of dictionaries with keys 'start', 'symbol' and 'next'. All 3 are strings. 'start_state' is string and rest are sets. """ # Dictionary for storing states, alphabet, rules, starting state and # finishing state. input_data = {"states":set(), "alphabet":set(), "rules":list(), "start_state":str(), "fin_states":set()} # Regex pattern for validing state variable pattern = re.compile(r"[_]{0}[aA-zZ]+\w*[_]{0}") ident = str() # Variable for temporary storing usefull data state = -1 # Represents current state of state machine next_state = 0 # Represents next state expected_bracket_open = True # Tells if expected character is ( expected_bracket_close = False # Tells if expected character is ) expected_brace_open = False # Tells if expected character is { expected_comma = False # Tells if expected character is , expected_apostrophe = False # Tells if expected character is ' data = enumerate(data) # String is not iterable, but function next is used # State machine itself. i is index, char is substring of string with length 1 for i, char in data: if state == 0: # State 0 represents loading set of states. if expected_brace_open: # Reading opening brase of set if char != "{": err("Missing opening brace in input source.", 60) expected_brace_open = False elif char == "}": expected_comma = True # Comma need to be inserted state = -1 # Switching to default state next_state = 1 # Setting next state else: ident = "" while char != ",": # Reading state identificator if char == "}": # Last state in set was read expected_comma = True # Comma need to be inserted state = -1 # Switching to default state next_state = 1 # Setting next state break else: ident += char i, char = next(data) # Reading next char if char is None: # End of source was reached err("Invalid imput source.", 60) regex = pattern.match(ident) if not regex or regex.group(0) != ident: # Testing validity of identificator err("'%s' is invalid name of state."%(ident), 60) input_data["states"].add(ident) # Adding state into set elif state == 1: # State 1 represents loading alphabet if expected_brace_open: # reading opening brace of set if char != "{": err("Missing opening brace in input source.", 60) expected_brace_open = False elif char == "}": # Set is empty err("Input alphabet is empty.", 61) else: # Reading symbol if char != "'": # 1st apostrophe err("Missing apostrophe in input source.", 60) i, char = next(data) if (char == "'"): # 2nd apostrophe i, char = next(data) if (char != "'"): # 3rd apostrophe if char != "," and char != "}": err("Invalid member of alphabet.", 60) else: ident = "epsilon" input_data["alphabet"].add(ident) else: ident = "''" elif char is None: # End of source is reached err("Invalid input source.", 60) else: # Char is nothing special ident = char if ident != "epsilon": i, char = next(data) if char != "'": # Checking ending apostrophe err("Missing apostrophe in input source.", 60) input_data["alphabet"].add(ident) # Adding symbol into set i, char = next(data) if char == ",": # Next sybol is expected pass elif char == "}": # End of set next_state = 2 # Setting next state expected_comma = True # Comma need to be inserted state = -1 # Switching to default state else: err("Invalid input source", 60) elif state == 2: # State 2 represents loading rules if expected_brace_open: # Set of rules starts with { if char != "{": err("Missing opening brace in input source.", 60) expected_brace_open = False elif char == "}": # Set is empty next_state = 3 # Setting next state expected_comma = True # Comma need to be inserted state = -1 # Switching to default state else: # ident will now represents dictionary with 3 items: # starting state, read symbol and next state ident = {"start":str(), "symbol":str(), "next":str()} while char != "'": # Loading starting state ident["start"] += char i, char = next(data) if char is None: # End of source was reached err("Invalid imput source.", 60) regex = pattern.match(ident["start"]) if not regex or regex.group(0) != ident["start"]: # Validing identificator err("'%s' is invalid name of state."%(ident["start"]), 60) if not (ident["start"] in input_data["states"]): # Checking if state is declareted err("State '%s' is not declareted in states."%(ident["start"]), 61) i, char = next(data) # Reading symbol if char == "'": # 2nd apostrophe i, char = next(data) if char != "'": # 3rd apostrophe if char != "-": err("Missing apostrophe in input source.", 60) else: ident["symbol"] = "epsilon" else: ident["symbol"] = "''" else: # Symbol is nothing special ident["symbol"] = char if not(ident["symbol"] in input_data["alphabet"]): # Checking if symbol is declareted err("Symbol '%s' is not declareted in input alphabet."%(ident["symbol"]), 61) if ident["symbol"] != "epsilon": i, char = next(data) if (char != "'"): # Checking presence of ending apostrophe err("Missing apostrophe in input source.", 60) i, char = next(data) if char != "-": # Checking presence of -> err("Invalid syntax in set of rules", 60) i, char = next(data) if char != ">": # Checking presence of -> err("Invalid syntax in set of rules", 60) i, char = next(data) while char != ",": # Reading next state if char is None: # End of source was reached err("Invalid input source.", 60) elif char == "}": # End of set was reached next_state = 3 # Setting next state expected_comma = True # Comma needs to be inserted state = -1 # Switching to current state break else: ident["next"] += char i, char = next(data) regex = pattern.match(ident["next"]) if not regex or regex.group(0) != ident["next"]: # Validing state err("'%s' is invalid name of state."%(ident["next"]), 60) if not(ident["next"] in input_data["states"]): # Checking if state is declareted err("State '%s' is not declareted in states."%(ident["next"]), 61) if not(ident in input_data["rules"]): # Avoiding multiple rules declaration input_data["rules"].append(ident) elif state == 3: # State 3 represents reading starting state ident = "" while char != ",": # Reading state identificator ident += char i, char = next(data) if char is None: # End of source reached err("Invalid imput source.", 60) regex = pattern.match(ident) if not regex or regex.group(0) != ident: # Validing identificator err("'%s' is invalid name of state."%(ident), 60) if not(ident in input_data["states"]): # Checking if state is declareted err("State '%s' is not declareted in states."%(ident), 61) input_data["start_state"] = ident # adding state state = 4 # Switching to next state expected_brace_open = True # Comma was read, brace is expected elif state == 4: # State 4 represents loading finishing states if expected_brace_open: # Reading starting brace of set if char != "{": err("Missing opening brace in input source.", 60) expected_brace_open = False elif char == "}": # set is emty state = -1 # Switching to default state expected_bracket_close = True # End of source expected else: ident = "" while char != ",": # Reading state identificator if char == "}": # End of set was reached state = -1 # Switching to default state expected_bracket_close = True # End of source expected break else: ident += char i, char = next(data) if char is None: err("Invalid imput source.", 60) regex = pattern.match(ident) if not regex or regex.group(0) != ident: # Validing state identificator err("'%s' is invalid name of state."%(ident), 60) if not (ident in input_data["states"]): # Checking is state was declareted err("Finishing state '%s' is not declareted in states."%(ident), 61) input_data["fin_states"].add(ident) elif state > 4: # states > 4 represents Error states err("Invalid input source.", 60) elif expected_comma: # Parsing comma between sets declaration if char != ",": err("Missing comma in input source.", 60) expected_comma = False state = next_state # Switching between states if state != 3: # State 3 does not represents sets and there is no brace expected_brace_open = True # Brace is expected elif expected_bracket_open: # Start of input source if char != "(": err("Missing opening bracked in input source.", 60) expected_brace_open = True # Next character must be { expected_bracket_open = False state = 0 # Switching from default state into state 0 elif expected_bracket_close: # End of inputsource if char != ")": err("Missing closing bracked in input source", 60) state = 5 # any other data will cause syntax error return input_data def write(args, finte_state_machine): """ Opens output file and writes into it. """ try: if args.output == sys.stdout: file = sys.stdout else: file = open(args.output, "w") except: err("Unable to open output file '%s'"%(args.output), 3) if args.finish: if finte_state_machine.non_finishing_states: file.write(str(list(finte_state_machine.non_finishing_states)[0])) else: file.write(str(0)) exit(0) if args.minimize: finite_state_machine.minimize() file.write(str(finite_state_machine)) else: file.write(str(finite_state_machine)) file.close() del sys.argv[0] # Deletes program name from arguments args = Arguments(sys.argv) # Parse arguments if args.help: # Prints help if needed Arguments.print_help() exit(0) finite_state_machine = parse_input(args) # Opens, closes and parses input source finite_state_machine = FiniteStateMachine(finite_state_machine) # Creates Finite state machine write(args, finite_state_machine) # Writes output
def generadorPares(limite): num = 1 while num < limite: yield num*2 num += 1 num_pares = generadorPares(10) """ for i in num_pares: print(i) """ print(next(num_pares)) print("Aquí podría ir mas código") print(next(num_pares))
#-------------------- #REMOVE THINGS #-------------------- # You can't grow a python list forever. Sooner or later you must remove elements and release disk and memory space # We will cover list.remove(), list.pop(index), and list.clear() #list.remove(element) - Removes the first occurance of an element (not all occruences) my_list = [1, 2, 3, 4, 5, 6, 7] print('My List:') print(my_list, '\n') # Remove ... my_list.remove(7) print('New List:') print(my_list, '\n') #NOTE: # Removing an element from a list has a linear runtime complexity # The growth of the runtime is restricted by a liner function O(n) for n elements - See O Notation (You have to check all elements in the list if the searched element doesn't exist ...) # If the list has 1000 elements, you need 1000 comparisons. For 2000 elements, you'll need 2000 comparisons ... #lst.pop() - This method removes AND returns the last element from an existing list #lst.pop(index) - Removes and returns the element at the position index # Make the list longer to play with ... my_list.extend([7, 8, 9, 10]) print('Longer List:') print(my_list, '\n') # Pop the last element my_list.pop() # Pop the all other even elements my_list.pop(0) # Now print to screen print('Cut Up List:') print(my_list, '\n') #lst.clear() - Removes all elements from an existing list (list becomes empty again) # Using lst.insert() and lst.append methods (to restore the list) my_list.insert(0, 1) my_list.append(10) print('Restored List:') print(my_list, '\n') # Now, let's use lst.clear my_list.clear() print('List Emptied:') print(my_list, '\n') #lst.remove(element) - Removes the first occurance of the PROVIDED element from an existing list # Repopulate list (using a for loop for fun) new_list = [] count = 1 while len(new_list) < 10: new_list.append(count) count += 1 print('Repopulated List:') print(new_list, '\n') # Now, let's remove a few elements new_list.remove(1) new_list.remove(3) new_list.remove(2) print(new_list, '\n') #CODE PUZZLE presidents = [ 'Clintont', 'Bush', 'Obama', 'Trump'] presidents_2 = presidents[:4] presidents_2.remove('Trump') print('Some Better Than Others:') print(presidents) # print what? #ANSWER # The computer prints ['Clinton', 'Bush', 'Obama', 'Trump'] # Becuase we manipulated presidents_2 - The inital presidents variable remained unchagned print('\n\n')
n = input('enter the number:') x=0 y=1 print str(x) print str(y) for x in range(n-2): z=x+y print str(z) x=y y=z
''' Distance between two cities is input through keyboard (in Km) convert - in m , ft , inches , cm ''' print("Welcome to conversion startup.We are happy to help you with all your conversions.") print("Enter name of the cities below(*OPTIONAL- PRESS ENTER TO SKIP*)") a = input("City1:") b = input("City2:") km = int(input("Enter Distance in kilometers:\t>>")) m = km * 1000 cm = m* 100 inch = cm/2.54 ft = inch/12 print("meters:%d\ncentimeters:%d\ninches:%d\nfeet:%d\n" %(m,cm,inch,ft)) print("Happy Journey")
__author__ = 'ariel' import sqlite3 with sqlite3.connect("cars.db") as connection: c = connection.cursor() # select only ford models c.execute("select * from inventory where Make = 'Ford'") ford = c.fetchall() for l in ford: print l[0], l[1], l[2]
#!/usr/bin/python3 num1 = input('输入的第一个数字:') num2 = input('输入的第2个数字:') print("\n两数相加结果:{} \n".format(float(num1) + float(num2))); print("两数相减结果:{} \n".format(float(num1) - float(num2))); print("两数相乘结果:{} \n".format(float(num1) * float(num2))); print("两数相除结果:{} \n".format(float(num1) / float(num2))); print("x的y次结果:{} \n".format(float(num1) ** float(num2))); print("两数的商:{} 和余数:{} \n".format(float(num1) // float(num2), float(num1) % float(num2)));
import matplotlib.pyplot as plt VAL = 2 DEGR = 9 def gorner(odds, x): p = float(1) i = 1 while i <= DEGR: p = p * x + odds[i] * VAL**i i = i + 1 print(x, ': ', p) return p def _main(): # interval [1.92, 2.08], step = 10**(-4) # given (x - 2)**9 odds = [1, -9, 36, -84, 126, -126, 84, -36, 9, -1] step = 10**(-4) print(step) start = 1.92 end = 2.08 p = [] x = start while(x <= end): plt.scatter(x, gorner(odds, x), s=1, c='black') x = x + step plt.plot(p) plt.show() if __name__ == '__main__': _main()